<?php
/**
 * Created by PhpStorm.
 * User: ly
 * Date: 2017\11\20 0020
 * Time: 16:06
 */

namespace backend\controllers;

use backend\models\PackageInitiationPlan;
use backend\models\User;
use common\models\InstationMessage;
use common\models\PackageCity;
use common\models\PackageInitiation;
use common\models\PackageInitiationIncome;
use common\models\PackageLike;
use backend\models\NewPackageOneForm;
use common\models\Country;
use common\models\Module;
use common\models\PackageLog;
use common\models\ProjectLog;
use common\models\ProjectPreEvaluationMortgage;
use common\models\ProjectTeam;
use common\models\ProjectUpdateLog;
use common\models\UserModel;
use common\models\Package;
use common\models\PackageTransfer;
use common\models\PackageTransferHistory;
use common\models\PackageTransferHistoryInit;
use common\models\ProjectPaymentCollection;
use common\models\ProjectPreEvaluationValueEvaluation;
use common\models\PackageUploadedExcel;
use common\models\UploadForm;
use kartik\dialog\Dialog;
use phpDocumentor\Reflection\Types\Null_;
use Yii;
use yii\db\ActiveQuery;
use yii\db\Query;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;
use yii\filters\VerbFilter;
use yii\db\Exception;
use backend\models\Excel;
use common\models\Project;
use common\models\Responses;
use yii\data\Pagination;
use yii\data\ActiveDataProvider;
use common\models\PackageUpdateLog;
use yii\widgets\LinkPager;
use backend\controllers\DtActionFilter;


class PackageController extends BaseController
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {

        return parent::behaviors();

//        return [
//            'verbs' => [
//                'class' => VerbFilter::className(),
//                'actions' => [
//                    'delete' => ['POST'],
//                ],
//            ],
//            'access' => [
//                'class' => AccessControl::className(),
//                'rules' => [
//                    'actions' => [],
//                    'allow' => true,
//                    'roles' => ['@'],
//                ],
//            ]
//        ];
    }

    /**
     * 资产包管理——填写新资产包基本信息
     * 总裁办、风控管理中心、财务部、技术部这四个部门默认具有权限
     *
     * @auth zhaoshouqiang
     * @return string|\yii\web\Response
     */
    public function actionIndex()
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(Yii::$app->user->loginUrl);
        } else {
            //所有部门人员
            $userModel = new UserModel();
//            $where = ['not in', 'department',
//                ['总裁办', '风控管理中心', '财务部', '技术部', '', '品牌部', '新大唐学院', '人力行政部', '加盟商-成都唐富团队', '南宁团队', '上海团队', '中山团队',
//                    '云南昆明', '成都唐富团队', '成都廖明松团队', '成都杨培军团队', '晋城团队', '淄博团队', '潍坊团队', '烟台团队', '石家庄团队', '贵阳团队', '郑州团队', '重庆杨洪胜团队', '重庆阳雪团队', '长春团团队',
//                    'ceooffice', 'windControlManagementCenter', 'finance', 'technology', 'brand', 'college', 'humanAdministration', 'ChengduTangFu', 'Nanning', 'platformConstruction', 'YangZhou',
//                ]];
            $where = ['in', 'department', ['project1', 'project2', 'project3', 'project6', 'foreignAffairsOffice']];
            $departments = $userModel->getDepartmentUsers($where);

            $model = new Package();
            $userId = Yii::$app->user->id;
            if ($post = Yii::$app->request->post()) {
                //访问类型
                $access = (int)$post['Package']['access'];
                switch ($access) {
                    case 0:
                        //$userList = $userModel->getList(array());
                        //$access_users = ArrayHelper::getColumn($userList, 'id');
                        $access_users = '';
                        break;
                    case 1:
                        //$data = ['or',
                        //    ['in', 'department', ['总裁办', '风控管理中心', '财务部', '技术部']],
                        //    ['in', 'department', ['ceooffice', 'windControlManagementCenter', 'finance', 'technology']]
                        //];
                        //$userList = $userModel->getList($data);
                        //$access_users = ArrayHelper::getColumn($userList, 'id');
                        $access_users = '';
                        break;
                    case 2:
                        //总裁办、风控管理中心、财务部、技术部等部门人员
                        $data = ['or',
                            ['in', 'department', ['总裁办', '风控管理中心', '财务部', '技术部',]],
                            //['in', 'department', ['ceooffice', 'windControlManagementCenter', 'finance', 'technology']]
                        ];
                        $userList = $userModel->getList($data);
                        $users = ArrayHelper::getColumn($userList, 'id');
                        //访问人员
                        if (!empty($post['Package']['access_users']) && is_array($post['Package']['access_users'])) {
                            foreach ($post['Package']['access_users'] as $k => $v) {
                                if ($v == '0') {
                                    unset($post['Package']['access_users'][$k]);
                                }
                            }
                            $access_users = join(',', array_unique(array_merge($post['Package']['access_users'], $users)));
                        } else {
                            $access_users = join(',', $users);
                        }
                        break;
                    default:
                }

                //删除项目部门
                unset($post['Package']['department']);

                $post['Package']['access_users'] = $access_users;
                $post['Package']['category'] = $model::CATEGORY_D;
                $post['Package']['state'] = $model::STATE_BASE;
                $post['Package']['origin'] = '';
                $post['Package']['owner'] = $userId;
                $post['Package']['created_at'] = date('Y-m-d H:i:s', time());
                $post['Package']['is_finished'] = 0; //0为未完成上传

                //如果已存在该名称且未完成则删除其操作
                $res = $model->validatorTitle($post['Package']['title']);
                if ($res['state']) {
                    if ($model->load($post) && $model->validate()) {
                        $re = $model->addPackage($model, $userId);
                        //添加资产包负责人
                        $initation = new PackageInitiation();
                        $initation->package_id = $model->id;
                        $initation->leader = ',' . $userId . ',';
                        $res = $initation->save();
                        if ($re['state'] && $res) {
                            return $this->redirect(['package/upload', 'packageid' => $model->id]);
                        } else {
                            $this->refresh();
                        }
                    }
                }
            }
            return $this->render('index', [
                'model' => $model,
                'departments' => $departments
            ]);
        }
    }

    /**
     * 验证资产包名称是否存在
     * @return array
     */
    public function actionValidateColumns()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $title = Yii::$app->request->post('title');
            $model = Package::find()->where(['title' => $title, 'is_finished' => 1])->one();
            if ($model !== null) {
                return Responses::response400('资产包名称的值"' . $title . '"已经被占用了。', true);
                //return Responses::response400('资产包已存在！', true);
            }
            return Responses::response200(array(), 1, '资产包名称不存在');
        }
    }

    /**
     * 资产包权限更新
     * @auth yangtao
     * @return \yii\web\Response
     */
    public function actionSetPermissions()
    {

        $this->layout = 'main2';
        $packageid = Yii::$app->request->get('package_id');
        $userModel = new UserModel();
        if ($post = Yii::$app->request->post()) {
            $id = $post['packageid'];
            $no_ajax = $post['no_ajax'];
            //访问类型
            $access = (int)$post['Package']['access'];
            switch ($access) {
                case 0:
                    $userList = $userModel->getList(array());
                    $access_users = ArrayHelper::getColumn($userList, 'id');
                    break;
                case 1:
                    $data = ['or',
                        ['in', 'department', ['总裁办', '风控管理中心', '财务部', '技术部']],
                        ['in', 'department', ['ceooffice', 'windControlManagementCenter', 'finance', 'technology']]
                    ];
                    $userList = $userModel->getList($data);
                    $access_users = ArrayHelper::getColumn($userList, 'id');
                    break;
                case 2:
                    //总裁办、风控管理中心、财务部、技术部等部门人员
                    $data = ['or',
                        ['in', 'department', ['总裁办', '风控管理中心', '财务部', '技术部']],
                        ['in', 'department', ['ceooffice', 'windControlManagementCenter', 'finance', 'technology']]
                    ];
                    $userList = $userModel->getList($data);
                    $users = ArrayHelper::getColumn($userList, 'id');
                    //访问人员
                    if (!empty($post['Package']['access_users']) && is_array($post['Package']['access_users'])) {
                        foreach ($post['Package']['access_users'] as $k => $v) {
                            if ($v == '0') {
                                unset($post['Package']['access_users'][$k]);
                            }
                        }
                        $access_users = array_unique(array_merge($post['Package']['access_users'], $users));
                    } else {
                        $access_users = $users;
                    }
                    break;
                default:
            }

            $model = new Package();
            if ($re = $model->setPermissionForPackage($access_users, $access, $id)) {
                if (Yii::$app->request->isAjax && !$no_ajax) {
                    if ($re['state']) {
                        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                        return ['status' => true, 'msg' => $re['msg']];
                    } else {
                        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                        return ['status' => false, 'msg' => $re['msg']];
                    }

                } else {
                    if ($re['state']) {
                        Yii::$app->getSession()->setFlash('success', $re['msg']);
                    } else {
                        Yii::$app->getSession()->setFlash('error', $re['msg']);
                    }
                    return $this->render("modal/asset-package-editing-permissions");

                }
            }
        }


        $data = Package::find()->where('id=:id', [':id' => $packageid])->asArray()->one();
        if (empty($data)) {
            throw new \Exception('error');
        }

        $result = \backend\controllers\DtActionFilter::checkPackage('package_permissions', $packageid);
        if (!$result) {
            if (Yii::$app->request->isAjax) {
                $response = Yii::$app->response;
                $response->format = \yii\web\Response::FORMAT_JSON;
                $response->data = ['status' => 'false', 'msg' => Yii::t('yii', 'You are not allowed to perform this action.')];
                $response->send();
                exit;
            } else {
                throw new  \yii\web\ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
        }

        if (Yii::$app->request->isAjax) {
            $no_ajax = 0;
        } else {
            $no_ajax = 1;
        }
        //所有部门人员
        $userModel = new UserModel();
//        $where = ['not in', 'department',
//            ['总裁办', '风控管理中心', '财务部', '技术部', '', '品牌部', '新大唐学院', '人力行政部',
//                'ceooffice', 'windControlManagementCenter', 'finance', 'technology', 'brand', 'college', 'humanAdministration', '',
//            ]];
        $where = ['in', 'department', ['project1', 'project2', 'project3', 'project6', 'foreignAffairsOffice']];
        $data['departments'] = $userModel->getDepartmentUsers($where);
        $data['access_users_ids'] = $data['access_users'] != "" ? explode(",", $data['access_users']) : "";
        $data['access_users'] = $this->getAccessUsers($data['access'], $data['access']);
        return $this->render("modal/asset-package-editing-permissions", ['no_ajax' => $no_ajax, 'packageid' => $data['id'], 'departments' => $data['departments'], 'access' => $data['access'], 'access_users_ids' => $data['access_users_ids']]);
    }

    /**
     * 资产包的关注
     * @return array
     * @throws \Exception
     */
    public function actionSetPackageLike()
    {
        //1关注
        $userId = Yii::$app->user->id;
        if (!$userId) {
            throw new \Exception('请先登录。');
        }
        $package_id = Yii::$app->request->get('package_id');
        $del = Yii::$app->request->get('del');
        $type = Yii::$app->request->get('type');
        if (empty($type)) {
            $type = 1;
        }
        if ($del) {
            $data = Package::find()->where(['id' => $package_id])->asArray()->one();
            if (empty($data)) {
                throw new \Exception('没有对应的资产包。');
            }
            $model = PackageLike::findOne(['package_id' => $package_id, 'user_id' => $userId, 'type' => $type]);
            $result = $model->delete();
            if ($result && empty($model->getErrors())) {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if ($type == 1) {
                    $packageLog = new PackageLog();
                    $packageLog->package_id = $package_id;
                    $packageLog->created_at = date('Y-m-d H:i:s');
                    $packageLog->user_id = $userId;
                    $packageLog->log = "取消关注成功";
                    $re = $packageLog->save();
                    if (!$re) {
                        throw new Exception('资产包日志保存失败');
                    }
                    return ['status' => true, 'msg' => '取消关注成功', 'img' => '/image/projectDetails/focus.png', 'type' => 0];
                } else {
                    $packageLog = new PackageLog();
                    $packageLog->package_id = $package_id;
                    $packageLog->created_at = date('Y-m-d H:i:s');
                    $packageLog->user_id = $userId;
                    $packageLog->log = "取消标记亮点成功";
                    $re = $packageLog->save();
                    if (!$re) {
                        throw new Exception('资产包日志保存失败');
                    }
                    return ['status' => true, 'msg' => '取消标记亮点成功', 'img' => '/image/projectDetails/liangDian.png', 'type' => 0];
                }

            } else {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if ($type == 1) {
                    return ['status' => false, 'msg' => '取消关注失败', 'img' => '/image/projectDetails/focus.png', 'type' => $type];
                } else {
                    return ['status' => false, 'msg' => '取消标记亮点失败', 'img' => '/image/projectDetails/liangDian.png', 'type' => $type];
                }
            }

        } else {
            $model = new PackageLike();
            $model->type = $type;
            $model->package_id = $package_id;
            $model->user_id = $userId;

            $result = $model->save();
            if ($result && empty($model->getErrors())) {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if ($type == 1) {
                    $packageLog = new PackageLog();
                    $packageLog->package_id = $package_id;
                    $packageLog->created_at = date('Y-m-d H:i:s');
                    $packageLog->user_id = $userId;
                    $packageLog->log = "关注成功";
                    $re = $packageLog->save();
                    if (!$re) {
                        throw new Exception('资产包日志保存失败');
                    }
                    return ['status' => true, 'msg' => '关注成功', 'img' => '/image/projectDetails/isfocus.png', 'type' => 1];
                } else {
                    $packageLog = new PackageLog();
                    $packageLog->package_id = $package_id;
                    $packageLog->created_at = date('Y-m-d H:i:s');
                    $packageLog->user_id = $userId;
                    $packageLog->log = "标记亮点成功";
                    $re = $packageLog->save();
                    if (!$re) {
                        throw new Exception('资产包日志保存失败');
                    }
                    return ['status' => true, 'msg' => '标记亮点成功', 'img' => '/image/projectDetails/isliangDian.png', 'type' => 1];
                }
            } else {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if ($type == 1) {
                    return ['status' => false, 'msg' => '关注失败', 'img' => '/image/projectDetails/focus.png', 'type' => $type];
                } else {
                    return ['status' => false, 'msg' => '标记亮点失败', 'img' => '/image/projectDetails/liangDian.png', 'type' => $type];
                }
            }

        }

    }

    /**
     * 上传excel，并且将数据插入package_uploaded_excel、 project表
     *
     * @auth zhaoshouqiang
     * @return string
     */
    public function actionUpload()
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(Yii::$app->user->loginUrl);
        } else {
            $userId = Yii::$app->user->id;
            $upload = new UploadForm();
            if (Yii::$app->request->isPost) {
                //ini_set('memory_limit', '2048M');

                $package_id = Yii::$app->request->post('package_id');
                $packageInfo = Package::findOne($package_id);
                $upload->xlsFile = UploadedFile::getInstance($upload, 'xlsFile');
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if ($upload->xlsFile && $upload->validate()) {
                    $oldFileName = $upload->xlsFile->baseName . '.' . $upload->xlsFile->extension;

                    /**中文上传解决，不改名字上传
                     * $filename='uploads/' . $model->xlsFile->baseName . '.' . $model->xlsFile->extension;
                     * $filename=iconv("UTF-8","gb2312",$filename);
                     * $model->xlsFile->saveAs($filename);
                     */
                    //重命名的文件上传
                    $filename = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $upload->xlsFile->extension;
                    $webroot = Yii::getAlias('@webroot');
                    $path = str_replace('\\', '/', $webroot . '/' . $upload::PATHFILE);
                    if (!is_dir($path)) {
                        mkdir($path);
                    }
                    $file = $path . $filename;
                    $re = $upload->xlsFile->saveAs($file);
                    if (!$re) {
                        return Responses::responseError(array('oldFileName' => $oldFileName), '上传模板【' . $oldFileName . '】失败', true);
                    }

                    $transaction = Yii::$app->db->beginTransaction();
                    try {
                        $current_date = date('Y-m-d H:i:s', time());
                        $packageUploadedExcel = new PackageUploadedExcel();
                        $packageUploadedExcel->file_name = $oldFileName;
                        $packageUploadedExcel->file_save_name = $filename;
                        $packageUploadedExcel->imported = 1; //是否入库：1是2否，默认是
                        $packageUploadedExcel->owner = $userId;  //操作人
                        $packageUploadedExcel->package_id = $package_id;
                        $packageUploadedExcel->created_at = $current_date;
                        if (!$packageUploadedExcel->save()) {
                            $error = $packageUploadedExcel->getFirstErrors();
                            $msg = '';
                            foreach ($error as $value) {
                                $msg .= $value;
                            }
                            throw new Exception($oldFileName . '上传失败，失败原因，' . $msg);
                        }

                        //现在只读了sheet1表数据
                        $excel = new Excel();
                        $data = $excel->getExcelData($file);

                        if (!empty($data)) {
                            $tbname = ['借款人名称', '本金', '利息', '诉讼状态', '保证人/抵押人', '担保方式', '是否亮点', '项目总监', '项目经理', '团队成员', '访问权限'];//表头模板
                            if (count($data[1]) == 11 && $data[1][0] == $tbname[0] && $data[1][1] == $tbname[1] && $data[1][2] == $tbname[2] && $data[1][3] == $tbname[3] && $data[1][4] == $tbname[4] && $data[1][5] == $tbname[5] && $data[1][6] == $tbname[6] && $data[1][7] == $tbname[7] && $data[1][8] == $tbname[8] && $data[1][9] == $tbname[9]) {
                                //从第二行开始
                                unset($data[1]);
                                //$count = count($data);
                                $count = 0;
                                $projectTeamModel = new ProjectTeam();
                                foreach ($data as $key => $value) {
                                    if (!empty($value) && ($value[0] != '' || $value[1] != '' || $value[2] != '' || $value[3] != '' || $value[4] != '' || $value[5] != '')) {
//                                        if (empty($value[0]) || empty($value[1]) || !is_numeric($value[1])) {
//                                            throw new \Exception('第 ' . $key . ' 行借款人名称、本金不能为空，且本金必须是数字');
//                                        }
                                        if (empty($value[0])) {
                                            throw new \Exception('第 ' . $key . ' 行借款人名称不能为空');
                                        }

                                        if (strlen($value[1]) > 0 && !is_numeric($value[1])) {
                                            throw new \Exception('第 ' . $key . ' 行本金不能为空，且本金必须是数字');
                                        }

                                        if (!empty($value[2])) {
                                            if (!is_numeric($value[2])) {
                                                throw new \Exception('第 ' . $key . ' 行利息不为空时，必须是数字');
                                            }
                                        } else {
                                            $value[2] = '0';
                                        }

                                        if (!empty($value[3]) && !in_array($value[3], array('未诉', '已诉', '部分诉讼'))) {
                                            throw new \Exception('第 ' . $key . ' 行请选择诉讼状态');
                                        }

                                        $project = new Project();
                                        $project->package_id = $package_id;
                                        $project->title = $value[0];
                                        $project->borrower = $value[0];
                                        $project->principal = $value[1];
                                        $project->interest = $value[2];
                                        $project->created_at = $current_date;
                                        $project->type = 1; //默认混合类
                                        //$project->category = $packageInfo->category; //资产类型
                                        $project->access = $packageInfo->access;
                                        $project->access_users = $packageInfo->access_users;
                                        switch ($value[3]) {
                                            case '未诉':
                                                $project->is_suit = Project::IS_SUIT_FALSE;
                                                break;
                                            case '已诉':
                                                $project->is_suit = Project::IS_SUIT_TRUE;
                                                break;
                                            case '部分诉讼':
                                                $project->is_suit = Project::SECTION_SUIT;
                                                break;
                                            default:
                                                $project->is_suit = -1;  //默认值
                                        }

                                        $project->guarantor = $value[4] ? $value[4] : '';
                                        $project->warranty = $value[5] ? $value[5] : '';
                                        $project->upload_id = $packageUploadedExcel->id;
                                        $project_is_highlight = array_flip(Yii::$app->params['project_is_highlight']);
                                        $project->is_highlights = $project_is_highlight[$value[6]];

                                        $projectTeam = clone $projectTeamModel;
                                        if ($value[10]) {
                                            $project->access = 2;
                                            $project->access_users = $projectTeam->getUserId($value[10]);
                                        }

                                        if ($project->save()) {
                                            //团队成员
                                            $projectTeam = clone $projectTeamModel;
                                            $projectTeam->project_id = $project->id;
                                            $projectTeam->manager = $value[7] ? $projectTeam->getUserId($value[7]) : ''; //项目总监
                                            $projectTeam->owner = $value[8] ? $projectTeam->getUserId($value[8]) : ''; //项目经理
                                            $projectTeam->partner = $value[9] ? $projectTeam->getUserId($value[9]) : ''; //项目协助人员
                                            $projectTeam->updated_at = date('Y-m-d H:i:s');
                                            $projectTeam->save();

                                            /*
                                                                                        //添加项目操作日志
                                                                                        $projectLog = new ProjectLog();
                                                                                        $projectLog->project_id = $project->id;
                                                                                        $projectLog->created_at = date('Y-m-d H:i:s', time());
                                                                                        $projectLog->user_id = Yii::$app->user->id;
                                                                                        $projectLog->log = '导入新项目【' . $project->title . '】';
                                                                                        if (!$projectLog->save()) {
                                                                                            throw new Exception('项目操作日志保存失败');
                                                                                        }*/
                                        } else {
                                            $error = $project->getFirstErrors();
                                            $msg = '';
                                            foreach ($error as $val) {
                                                $msg .= $val;
                                            }
                                            throw new Exception('第 ' . $key . ' 行导入项目失败，错误原因，' . $msg);
                                        }
                                        $count++;
                                    } else {
                                        if ($value[0] == '' && $value[1] == '' && $value[2] == '' && $value[3] == '' && $value[4] == '' && $value[5] == '') {
                                            continue;
                                        }
                                        throw new Exception('第 ' . $key . ' 行为空行');
                                    }
                                }

                                $transaction->commit();
                                return Responses::response200(array('oldFileName' => $oldFileName, 'fileName' => $filename), 1, '导入项目数据' . $count . '条');
                            } else {
                                throw new \Exception('文件表头依次是，借款人名称，本金，利息，诉讼状态，保证人/抵押人，担保方式', '是否亮点', '项目总监', '项目经理', '团队成员', '访问权限');
                            }
                        } else {
                            throw new \Exception('文件不能为空');
                        }
                    } catch (\Exception $e) {
                        $transaction->rollBack();
                        $message = $e->getMessage();
                        return Responses::responseError(array('oldFileName' => $oldFileName, 'fileName' => $filename), $message, true);
                    } catch (\Throwable $e) {
                        $transaction->rollBack();
                        $message = $e->getMessage();
                        return Responses::responseError(array('oldFileName' => $oldFileName, 'fileName' => $filename), $message, true);
                    }
                } else {
                    $error = $upload->getFirstErrors();
                    $msg = '';
                    foreach ($error as $value) {
                        $msg .= $value;
                    }

                    return Responses::response400($msg . '，请下载模板完善上传', true);
                }
            } else {
                $package_id = Yii::$app->request->get('packageid');
                return $this->render('upload', [
                    'upload' => $upload,
                    'packageid' => $package_id,
                ]);
            }
        }
    }

    /**
     * 上传excel，并且将数据插入package_uploaded_excel、 project表
     *      需要判断项目名称是否相同，相同过滤，写入数据库且is_finished=1
     * @auth zhaoshouqiang
     * @return string
     */
    public function actionSyncUploadExcel()
    {
        $userId = Yii::$app->user->id;
        $upload = new UploadForm();
        if (Yii::$app->request->isPost) {
            //ini_set('memory_limit', '2048M');

            $package_id = Yii::$app->request->post('package_id');
            $packageInfo = Package::findOne($package_id);
            $upload->xlsFile = UploadedFile::getInstance($upload, 'xlsFile');
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            if ($upload->xlsFile && $upload->validate()) {
                $oldFileName = $upload->xlsFile->baseName . '.' . $upload->xlsFile->extension;

                //重命名的文件上传
                $filename = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $upload->xlsFile->extension;
                $webroot = Yii::getAlias('@webroot');
                $path = str_replace('\\', '/', $webroot . '/' . $upload::PATHFILE);
                if (!is_dir($path)) {
                    mkdir($path);
                }
                $file = $path . $filename;
                $re = $upload->xlsFile->saveAs($file);
                if (!$re) {
                    return Responses::responseError(array('oldFileName' => $oldFileName), '上传模板【' . $oldFileName . '】失败', true);
                }

                //资产包中所有项目清单
                $projectList = (new yii\db\Query())
                    ->select(['id', 'title'])
                    ->from(Project::tableName())
                    ->where(['package_id' => $package_id])
                    ->all();
                if (!empty($projectList)) {
                    $projectArray = ArrayHelper::getColumn($projectList, 'title');
                }

                $transaction = Yii::$app->db->beginTransaction();
                try {
                    $current_date = date('Y-m-d H:i:s', time());
                    $packageUploadedExcel = new PackageUploadedExcel();
                    $packageUploadedExcel->file_name = $oldFileName;
                    $packageUploadedExcel->file_save_name = $filename;
                    $packageUploadedExcel->imported = 1; //是否入库：1是2否，默认是
                    $packageUploadedExcel->owner = $userId;  //操作人
                    $packageUploadedExcel->package_id = $package_id;
                    $packageUploadedExcel->created_at = $current_date;
                    if (!$packageUploadedExcel->save()) {
                        $error = $packageUploadedExcel->getFirstErrors();
                        $msg = '';
                        foreach ($error as $value) {
                            $msg .= $value;
                        }
                        throw new Exception($oldFileName . '上传失败，失败原因，' . $msg);
                    }

                    //现在只读了sheet1表数据
                    $excel = new Excel();
                    $data = $excel->getExcelData($file);

                    if (!empty($data)) {
                        $tbname = ['借款人名称', '本金', '利息', '诉讼状态', '保证人/抵押人', '提保方式'];//表头模板
                        if (count($data[1]) == 6 && $data[1][0] == $tbname[0] && $data[1][1] == $tbname[1] && $data[1][2] == $tbname[2] && $data[1][3] == $tbname[3] && $data[1][4] == $tbname[4]) {
                            //从第二行开始
                            unset($data[1]);
                            //$count = count($data);
                            $count = 0;
                            foreach ($data as $key => $value) {
                                if (!empty($projectArray) && in_array($value[0], $projectArray)) continue;

                                if (!empty($value) && ($value[0] != '' || $value[1] != '' || $value[2] != '' || $value[3] != '' || $value[4] != '' || $value[5] != '')) {
                                    if (empty($value[0])) {
                                        throw new \Exception('第 ' . $key . ' 行借款人名称不能为空');
                                    }

                                    if (strlen($value[1]) > 0 && !is_numeric($value[1])) {
                                        throw new \Exception('第 ' . $key . ' 行本金不能为空，且本金必须是数字');
                                    }

                                    if (!empty($value[2])) {
                                        if (!is_numeric($value[2])) {
                                            throw new \Exception('第 ' . $key . ' 行利息不为空时，必须是数字');
                                        }
                                    } else {
                                        $value[2] = '0';
                                    }

                                    if (!empty($value[3]) && !in_array($value[3], array('未诉', '已诉', '部分诉讼'))) {
                                        throw new \Exception('第 ' . $key . ' 行请选择诉讼状态');
                                    }

                                    $project = new Project();
                                    $project->package_id = $package_id;
                                    $project->title = $value[0];
                                    $project->borrower = $value[0];
                                    $project->principal = $value[1];
                                    $project->interest = $value[2];
                                    $project->created_at = $current_date;
                                    $project->type = 1; //默认混合类
                                    //$project->category = $packageInfo->category; //资产类型
                                    $project->access = $packageInfo->access;
                                    $project->access_users = $packageInfo->access_users;
                                    switch ($value[3]) {
                                        case '未诉':
                                            $project->is_suit = Project::IS_SUIT_FALSE;
                                            break;
                                        case '已诉':
                                            $project->is_suit = Project::IS_SUIT_TRUE;
                                            break;
                                        case '部分诉讼':
                                            $project->is_suit = Project::SECTION_SUIT;
                                            break;
                                        default:
                                            $project->is_suit = -1;  //默认值
                                    }

                                    $project->guarantor = $value[4] ? $value[4] : '';
                                    $project->warranty = $value[5] ? $value[5] : '';
                                    $project->upload_id = $packageUploadedExcel->id;
                                    $project->is_finished = 1;

                                    if ($project->save()) {
                                        //添加项目操作日志
                                        /*$projectLog = new ProjectLog();
                                        $projectLog->project_id = $project->id;
                                        $projectLog->created_at = date('Y-m-d H:i:s', time());
                                        $projectLog->user_id = Yii::$app->user->id;
                                        $projectLog->log = '导入新项目【' . $project->title . '】';
                                        if (!$projectLog->save()) {
                                            throw new Exception('项目操作日志保存失败');
                                        }*/
                                    } else {
                                        $error = $project->getFirstErrors();
                                        $msg = '';
                                        foreach ($error as $value) {
                                            $msg .= $value;
                                        }
                                        throw new Exception('第 ' . $key . ' 行导入项目失败，错误原因，' . $msg);
                                    }
                                    $count++;
                                } else {
                                    if ($value[0] == '' && $value[1] == '' && $value[2] == '' && $value[3] == '' && $value[4] == '' && $value[5] == '') {
                                        continue;
                                    }
                                    throw new Exception('第 ' . $key . ' 行为空行');
                                }
                            }

                            $transaction->commit();
                            return Responses::response200(array('oldFileName' => $oldFileName, 'fileName' => $filename), 1, '导入项目数据' . $count . '条');
                        } else {
                            throw new \Exception('文件表头依次是，借款人名称，本金，利息，诉讼状态，保证人/抵押人，担保方式');
                        }
                    } else {
                        throw new \Exception('文件不能为空');
                    }
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    $message = $e->getMessage();
                    return Responses::responseError(array('oldFileName' => $oldFileName, 'fileName' => $filename), $message, true);
                } catch (\Throwable $e) {
                    $transaction->rollBack();
                    $message = $e->getMessage();
                    return Responses::responseError(array('oldFileName' => $oldFileName, 'fileName' => $filename), $message, true);
                }
            } else {
                $error = $upload->getFirstErrors();
                $msg = '';
                foreach ($error as $value) {
                    $msg .= $value;
                }
                return Responses::response400($msg . '，请下载模板完善上传', true);
            }
        } else {
            $package_id = Yii::$app->request->get('packageid');
            return $this->render('upload2', [
                'upload' => $upload,
                'packageid' => $package_id,
            ]);
        }

    }

    /**
     * 上传excel，并且将数据插入package_uploaded_excel、 project表(模态)
     *     需要判断项目名称是否相同，相同过滤，写入数据库且is_finished=1
     * @auth zhaoshouqiang
     * @return string
     */
    public function actionUploadModal()
    {
        $userId = Yii::$app->user->id;
        $upload = new UploadForm();
        if (Yii::$app->request->isPost) {
            //ini_set('memory_limit', '2048M');

            $package_id = Yii::$app->request->post('package_id');
            $packageInfo = Package::findOne($package_id);
            $upload->xlsFile = UploadedFile::getInstance($upload, 'xlsFile');
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            if ($upload->xlsFile && $upload->validate()) {
                $oldFileName = $upload->xlsFile->baseName . '.' . $upload->xlsFile->extension;

                //重命名的文件上传
                $filename = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $upload->xlsFile->extension;
                $webroot = Yii::getAlias('@webroot');
                $path = str_replace('\\', '/', $webroot . '/' . $upload::PATHFILE);
                if (!is_dir($path)) {
                    mkdir($path);
                }
                $file = $path . $filename;
                $re = $upload->xlsFile->saveAs($file);
                if (!$re) {
                    return Responses::responseError(array('oldFileName' => $oldFileName), '上传模板【' . $oldFileName . '】失败', true);
                }

                //资产包中所有项目清单
                $projectList = (new yii\db\Query())
                    ->select(['id', 'title'])
                    ->from(Project::tableName())
                    ->where(['package_id' => $package_id])
                    ->all();
                if (!empty($projectList)) {
                    $projectArray = ArrayHelper::getColumn($projectList, 'title');
                }

                $transaction = Yii::$app->db->beginTransaction();
                try {
                    $current_date = date('Y-m-d H:i:s', time());
                    $packageUploadedExcel = new PackageUploadedExcel();
                    $packageUploadedExcel->file_name = $oldFileName;
                    $packageUploadedExcel->file_save_name = $filename;
                    $packageUploadedExcel->imported = 1; //是否入库：1是2否，默认是
                    $packageUploadedExcel->owner = $userId;  //操作人
                    $packageUploadedExcel->package_id = $package_id;
                    $packageUploadedExcel->created_at = $current_date;
                    if (!$packageUploadedExcel->save()) {
                        $error = $packageUploadedExcel->getFirstErrors();
                        $msg = '';
                        foreach ($error as $value) {
                            $msg .= $value;
                        }
                        throw new Exception($oldFileName . '上传失败，失败原因，' . $msg);
                    }

                    //现在只读了sheet1表数据
                    $excel = new Excel();
                    $data = $excel->getExcelData($file);
                    if (!empty($data)) {
                        $tbname = ['借款人名称', '本金', '利息', '诉讼状态', '保证人/抵押人', '担保方式', '是否亮点', '项目总监', '项目经理', '团队成员', '访问权限'];//表头模板
                        if (count($data[1]) == 11 && $data[1][0] == $tbname[0] && $data[1][1] == $tbname[1] && $data[1][2] == $tbname[2] && $data[1][3] == $tbname[3] && $data[1][4] == $tbname[4] && $data[1][5] == $tbname[5] && $data[1][6] == $tbname[6] && $data[1][7] == $tbname[7] && $data[1][8] == $tbname[8] && $data[1][9] == $tbname[9]) {
                            //从第二行开始
                            unset($data[1]);
                            //$count = count($data);
                            $count = 0;
                            $projectTeamModel = new ProjectTeam();
                            foreach ($data as $key => $value) {
                                if (!empty($projectArray) && in_array($value[0], $projectArray)) continue;

                                if (!empty($value) && ($value[0] != '' || $value[1] != '' || $value[2] != '' || $value[3] != '' || $value[4] != '' || $value[5] != '')) {
                                    if (empty($value[0])) {
                                        throw new \Exception('第 ' . $key . ' 行借款人名称不能为空');
                                    }

                                    if (strlen($value[1]) > 0 && !is_numeric($value[1])) {
                                        throw new \Exception('第 ' . $key . ' 行本金不能为空，且本金必须是数字');
                                    }

                                    if (!empty($value[2])) {
                                        if (!is_numeric($value[2])) {
                                            throw new \Exception('第 ' . $key . ' 行利息不为空时，必须是数字');
                                        }
                                    } else {
                                        $value[2] = '0';
                                    }

                                    if (!empty($value[3]) && !in_array($value[3], array('未诉', '已诉', '部分诉讼'))) {
                                        throw new \Exception('第 ' . $key . ' 行请选择诉讼状态');
                                    }

                                    $project = new Project();
                                    $project->package_id = $package_id;
                                    $project->title = $value[0];
                                    $project->borrower = $value[0];
                                    $project->principal = $value[1];
                                    $project->interest = $value[2];
                                    $project->created_at = $current_date;
                                    $project->type = 1; //默认混合类
                                    //$project->category = $packageInfo->category; //资产类型
                                    $project->access = $packageInfo->access;
                                    $project->access_users = $packageInfo->access_users;
                                    switch ($value[3]) {
                                        case '未诉':
                                            $project->is_suit = Project::IS_SUIT_FALSE;
                                            break;
                                        case '已诉':
                                            $project->is_suit = Project::IS_SUIT_TRUE;
                                            break;
                                        case '部分诉讼':
                                            $project->is_suit = Project::SECTION_SUIT;
                                            break;
                                        default:
                                            $project->is_suit = -1;  //默认值
                                    }

                                    $project->guarantor = $value[4] ? $value[4] : '';
                                    $project->warranty = $value[5] ? $value[5] : '';
                                    $project->upload_id = $packageUploadedExcel->id;
                                    $project->is_finished = 1;
                                    $project_is_highlight = array_flip(Yii::$app->params['project_is_highlight']);
                                    $project->is_highlights = $project_is_highlight[$value[6]];
                                    $projectTeam = clone $projectTeamModel;


                                    if (trim($value[10])) {
                                        $project->access = 2;
                                        $project->access_users = $projectTeam->getUserId($value[10]);
                                    }

                                    if ($project->save()) {
                                        //团队成员
                                        $projectTeam = clone $projectTeamModel;
                                        $projectTeam->project_id = $project->id;
                                        $projectTeam->manager = $value[7] ? $projectTeam->getUserId($value[7]) : ''; //项目总监
                                        $projectTeam->owner = $value[8] ? $projectTeam->getUserId($value[8]) : ''; //项目经理
                                        $projectTeam->partner = $value[9] ? $projectTeam->getUserId($value[9]) : ''; //项目协助人员
                                        $projectTeam->updated_at = date('Y-m-d H:i:s');
                                        $projectTeam->save();
                                        //添加项目操作日志
                                        /*$projectLog = new ProjectLog();
                                        $projectLog->project_id = $project->id;
                                        $projectLog->created_at = date('Y-m-d H:i:s', time());
                                        $projectLog->user_id = Yii::$app->user->id;
                                        $projectLog->log = '导入新项目【' . $project->title . '】';
                                        if (!$projectLog->save()) {
                                            throw new Exception('项目操作日志保存失败');
                                        }*/
                                    } else {
                                        $error = $project->getFirstErrors();

                                        $msg = '';
                                        foreach ($error as $val) {
                                            $msg .= $val;
                                        }
                                        throw new Exception('第 ' . $key . ' 行导入项目失败，错误原因，' . $msg);
                                    }
                                    $count++;
                                } else {
                                    if ($value[0] == '' && $value[1] == '' && $value[2] == '' && $value[3] == '' && $value[4] == '' && $value[5] == '') {
                                        continue;
                                    }
                                    throw new Exception('第 ' . $key . ' 行为空行');
                                }
                            }

                            $transaction->commit();

                            return Responses::response200(array('oldFileName' => $oldFileName, 'fileName' => $filename), 1, '导入项目数据' . $count . '条');
                        } else {
                            throw new \Exception('文件表头依次是，借款人名称，本金，利息，诉讼状态，保证人/抵押人，担保方式，是否亮点，项目总监，项目经理，团队成员，访问权限');
                        }
                    } else {
                        throw new \Exception('文件不能为空');
                    }
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    $message = $e->getMessage();
                    return Responses::responseError(array('oldFileName' => $oldFileName, 'fileName' => $filename), $message, true);
                } catch (\Throwable $e) {
                    $transaction->rollBack();
                    $message = $e->getMessage();
                    return Responses::responseError(array('oldFileName' => $oldFileName, 'fileName' => $filename), $message, true);
                }
            } else {
                $error = $upload->getFirstErrors();
                $msg = '';
                foreach ($error as $value) {
                    $msg .= $value;
                }
                return Responses::response400($msg . '，请下载模板完善上传', true);
            }
        }
    }

    /**
     * 下载资产包上传模板
     * @auth zhaoshouqiang
     */
    public function actionDownload()
    {
        $webroot = Yii::getAlias('@webroot');
        $file = $webroot . '/downloads/packageUpdateTemplate.xlsx';
        if (file_exists($file)) {
            Yii::$app->response->sendFile($webroot . '/downloads/packageUpdateTemplate.xlsx', '资产包上传模板.xlsx')->send();
        }
    }

    /**
     * 删除上传失败的excel文件
     */
    public function actionDelExcel()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $fileName = $page = Yii::$app->request->post('fileName');
            if ($fileName) {
                $webroot = Yii::getAlias('@webroot');
                $file = $webroot . '/uploads/' . $fileName;
                if (file_exists($file)) {

                    //删除上传excel与项目
                    $packageUploadExcel = PackageUploadedExcel::find()->where(array('file_save_name' => $fileName))->one();
                    if ($packageUploadExcel !== null) {
                        $projectList = (new yii\db\Query())->select(['id', 'upload_id'])
                            ->from(Project::tableName())
                            ->where(['upload_id' => $packageUploadExcel->id])
                            ->orderBy(['id' => SORT_DESC])
                            ->indexBy('id')
                            ->all();
                        if (!empty($projectList) && is_array($projectList)) {
                            foreach ($projectList as $value) {
                                $project = Project::findOne(['id' => $value['id']]);

                                $projectLog = new ProjectLog();
                                $projectLog->project_id = $project->id;
                                $projectLog->created_at = date('Y-m-d H:i:s', time());
                                $projectLog->user_id = Yii::$app->user->id;
                                $projectLog->log = '删除项目【' . $project->title . '】';
                                $projectLog->save();

                                $project->delete();
                            }
                        }
                        //Project::deleteAll(array('upload_id'=>$packageUploadExcel->id));//deleteAll方法不触发event事件，不会触发afterDelete方法

                        $packageUploadExcel->delete();
                    }

                    //删除文件
                    $res = unlink($file);
                    if ($res) {
                        return Responses::response200(array(), 1, '删除成功');
                    } else {
                        return Responses::response400('删除失败', 1);
                    }
                }
                return Responses::response400("{$fileName}该文件不存在", 1);
            } else {
                return Responses::response400('文件名不能为空', 1);
            }
        }
    }

    /*
    *新建资产包完善信息页基本信息展示
     * *传值package_id
     * * @auth ly
     */
    public function actionPerfectInfo()
    {
        if (Yii::$app->request->isGet && Yii::$app->request->get('packageid')) {
//            $packageid=Yii::$app->request->get('packageid');
            Yii::$app->session->set('packageid', Yii::$app->request->get('packageid'));
            $packageid = Yii::$app->session->get('packageid');
            // $packageid='1';
            /*获取资产包基本信息*/
            $data = Package::find()->where('id=:id', [':id' => $packageid])->asArray()->one();
            if (!$data) {
                return new Exception('该资产包不存在');
            }

            if ($data['is_finished'] == 1) {
                return $this->redirect(['my-package/get-my-package?packageGroup=2']);
            }

            /*可访问人员名单*/
            $data['access_users'] = $this->getAccessUsers($data['access'], $data['access_users']);
            /*获取省份列表*/
            $countrylist['province'] = Country::find()->where("pid=0")->asArray()->all();//(new Country())->getName($data['province']);
            $countrylist['city'] = Country::find()->where("pid=:pid", [':pid' => $data['province']])->asArray()->all();//(new Country())->getName($data['city']);
            $data['countrylist'] = $countrylist;
            /*show转让信息*/
            //$data['transfer'] = $this->getTransfer($packageid);getTransfer
            $data['transfer'] = (new PackageTransfer())->getTransfer($packageid);
            /*show流转、前置处理记录*/
            $history = PackageTransferHistory::find()->where("package_id=$packageid")->orderBy('order ASC')->asArray()->all();
            $data['history'] = $history;
            /*show
            *获取上传项目文件xls的项目列表 */
            $projectlist = Project::find()->where("package_id=:package_id", [':package_id' => $packageid]);
            $pages = new Pagination(['totalCount' => $projectlist->count(), 'pageSize' => 10]);    //$pageSize实例化分页类,带上参数(总条数,每页显示条数)
            $data_array = $projectlist->offset($pages->offset)->limit($pages->limit)->asArray()->all();
            $data['projectlist'] = $data_array;
            if (Yii::$app->request->isAjax) {
                return $this->renderPartial('package-info-data', [
                    'pages' => $pages,
                    'data' => $data
                ]);
            }
            return $this->render('package-info', ['data' => $data, 'pages' => $pages]);
        }
        return new Exception('访问网页有误');
    }

    /*获取公开部门显示结果*/
    private function getAccessUsers($access, $accessStr)
    {
        switch ($access) {
            case 2:
                $access_users = (new UserModel())->getUserStr($accessStr);//可访问的用户str
                break;
            case 1:
                $access_users = '私密';
                break;
            default:
                $access_users = '公司全体人员';
                break;
        }
        return $access_users;
    }

    /*获取市级地区列表---接口
    * * @auth ly
    */
    public function actionGetCountryList()
    {
        if (Yii::$app->request->isPost) {
            $pid = Yii::$app->request->post('id');
            $countrylist = Country::find()->where("pid=:pid", [':pid' => $pid])->asArray()->all();
            if (!empty($countrylist)) {
                $data = Responses::response200($countrylist, 0, 'success');
            } else {
                $data = Responses::response404();
            }
            return json_encode($data);
        }
    }

    /*计算时间差 （ly）*/
    public function timeDiff($begin_time, $end_time)
    {
        if ($begin_time < $end_time) {
            $starttime = $begin_time;
            $endtime = $end_time;
        } else {
            $starttime = $end_time;
            $endtime = $begin_time;
        }
        $timediff = $endtime - $starttime;
        $days = intval($timediff / 86400);
        $remain = $timediff % 86400;
        $hours = intval($remain / 3600);
        $remain = $remain % 3600;
        $mins = intval($remain / 60);
        $secs = $remain % 60;
        // $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
        $res = ($days > 0 ? $days . "天" : '') . ($hours > 0 ? $hours . "小时" : '') . ($mins > 0 ? $mins . "分钟" : '') . ($secs > 0 ? $secs . "秒" : '');
        return $res;
    }

    /*资产包详情页-show
    *  @auth ly
    */
    public function actionDetailInfo()
    {

        //-------------修改消息状态--变为已读----fly---------------------
        $messageState = Yii::$app->request->get('message_state', 1);
        $follow = Yii::$app->request->get('follow', 0);
        if ($messageState == 2) {
            $param['message_user_group_id'] = Yii::$app->request->get('message_user_group_id', 1);
            $user_id = \Yii::$app->user->getId();
            $state = 0;
            $instationMessageState = InstationMessage::readAdminMessage($param);
            if (!empty($follow)) {
                $param['user_id'] = Yii::$app->request->get('user_id', 1);
                $instationMessageState = InstationMessage::readLikeMessage($param);
            }
            if ($instationMessageState['code'] == 400) {
                return false;
            }
        }
        //-------------修改消息状态--变为已读----fly---------------------

        if (Yii::$app->request->isGet && Yii::$app->request->get('packageid')) {
            Yii::$app->session->set('packageid', Yii::$app->request->get('packageid'));
            $packageid = Yii::$app->session->get('packageid');
            // $packageid='1';
            /*show资产包基本信息*/
            $data = Package::find()->where('id=:id', [':id' => $packageid])->asArray()->one();
            if (!$data) {
                return new Exception('该资产包不存在');
            }
            /*获取资产包的更新时间和更新人员*/
            $updateRes = PackageUpdateLog::find()->with('userName')->where(['package_id' => $packageid])->limit(1)->orderBy('id desc')->asArray()->all();
            if ($updateRes) {
                $data['updateTime'] = [$this->timeDiff(strtotime($updateRes[0]['created_at']), time()), $updateRes[0]['userName']['realname']];
                $data['access_users_ids'] = $data['access_users'] != "" ? explode(",", $data['access_users']) : "";
            } else {
                $data['updateTime'] = 0;
                $data['access_users_ids'] = '';
            }
            //$data['updateTime']=[$this->timeDiff(strtotime($updateRes[0]['created_at']),time()),$updateRes[0]['userName']['realname']];
            // $updateRes[0]['created_at']  $updateRes[0]['userName']['realname']
            //$data['access_users_ids'] = $data['access_users'] != "" ? explode(",", $data['access_users']) : "";
            /*可访问人员名单 */
            // $data['access_users'] = $this->getAccessUsers($data['access'], $data['access_users']);
            /*根据资产包状态显示人员*/
            $data['avatar'] = (new Package())->getAvatar($data['state'], $data['owner'], $packageid);
            //是否关注 yt
            $data_like = PackageLike::find()->where(['package_id' => $packageid, 'type' => 1, 'user_id' => Yii::$app->user->id])->asArray()->one();
            if ($data_like['id']) {
                $data['flow'] = 1;
            } else {
                $data['flow'] = 0;
            }


            //获取自动计算列表
            $data['allCalculate'] = $this->getAllCalculate($packageid);
            //获取省名称
            $countrylist['province'] = (new Country())->getName($data['province']);
            //获取城市名称
            //$countrylist['city'] = (new Country())->getName($data['city']);

            //资产包城市多选
//            $list = Country::getTitleList();
//            $countrylist['city'] = '';
//            $packageCityList = (new Query())
//                ->select(['id', 'city_id'])
//                ->from(PackageCity::tableName())
//                ->where(['package_id'=>(int)$packageid])
//                ->orderBy(['id' => SORT_ASC])
//                ->all();
//            if (!empty($packageCityList)) {
//                $arr = array();
//                foreach ($packageCityList as $value) {
//                    $arr[] = $list[(int)$value['city_id']];
//                }
//                $countrylist['city'] = join('、', $arr);
//            }

            if ($data['city'] != '') {
                $arr = explode(',', $data['city']);
                $list = Country::getTitleList();
                $array = array();
                if (!empty($arr) && is_array($arr)) {
                    foreach ($arr as $value) {
                        if ($value > 0) {
                            $array[] = $list[(int)$value];
                        }
                    }
                }
                $countrylist['city'] = join('、', $array);
            } else {
                $countrylist['city'] = '';
            }

            $data['countrylist'] = $countrylist;

            /*show转让信息*/
            $data['transfer'] = (new PackageTransfer())->getTransfer($packageid);
            /*show流转、前置处理记录*/
            $history = PackageTransferHistory::find()->where("package_id=$packageid")->orderBy('order ASC')->asArray()->all();
            $data['history'] = $history;
            /*show项目列表--获取（保证类混合类）1和3 */
            // $searchModel=Project::find()->with('provinceName', 'cityName', 'lawsuit', 'evaluation', 'note');
            $projectListHH = Project::find()->with('provinceName', 'cityName', 'lawsuit', 'evaluation', 'note')->where(['<>', 'type', 2])->andWhere("package_id=$packageid")->orderBy(['is_highlights' => SORT_ASC, 'id' => SORT_DESC]);
            $projectListHHArray = new ActiveDataProvider([
                'query' => $projectListHH,
                'pagination' => [
                    'pagesize' => 10
                ]
            ]);
            /*show项目列表--获取（抵押类）2*/
            $projectListDY = Project::find()->with('provinceName', 'cityName', 'lawsuit', 'mortgage.seal.value', 'oValue', 'payment')->where(['type' => 2])->andWhere(["package_id" => $packageid])->orderBy(['is_highlights' => SORT_ASC, 'id' => SORT_DESC]);
            $pagesDY = new Pagination(['totalCount' => $projectListDY->count(), 'pageSize' => 10]);    //$pageSize实例化分页类,带上参数(总条数,每页显示条数)
            $projectListDYArray = $projectListDY->offset($pagesDY->offset)->limit($pagesDY->limit)->asArray()->all();

//            $projectListDY = (new \yii\db\Query())
//                ->from('project AS p')
//                ->select('
//                p.package_id,p.id,p.borrower,p.principal,p.interest,p.is_suit,p.management_status,p.enterprise,p.industry,p.guarantor,p.guarantor_status,p.mortgage_details,p.is_highlights,pc.title as pctitle,pcc.title as pcctitle,
//                l.judgement,l.execution,l.court,l.block,
//                m.mortgage_principal,m.mortgage_interest,s.mortgage_type,s.mortgage_owner,s.mortgage_code,s.mortgage_building_area,s.mortgage_land_area,s.maximum_mortgage,s.remaining_service_life,
//                s.is_first_mortgage,s.mortgage_future,s.mortgage_seal_order,s.is_first_seal,s.mortgage_seal_state,s.mortgage_order,s.mortgage_situation,
//                v.payment_reservation as vpayment_reservation,v.payment_radical as vpayment_radical,v.price_reason,
//                ov.bought_analysis,ov.bought_reservation,ov.bought_radical,s.mortgage_other_seal_order,s.mortgage_other_seal_state,
//                c.payment_reservation,c.payment_radical,c.payment_tax,c.payment_month,c.payment_analysis
//                ')
//                ->leftJoin('project_pre_evaluation_mortgage AS m', 'm.project_id = p.id')
//                ->leftJoin('project_pre_evaluation_seal as s', 's.mortgage_id=m.id')
//                ->leftJoin('project_pre_evaluation_lawsuit AS l', 'l.project_id = p.id')
//                ->leftJoin('project_pre_evaluation_value AS v', 'v.mortgage_id = m.id')
//                ->leftJoin('project_pre_evaluation_other_value AS ov', 'ov.project_id = p.id')
////                ->leftJoin('project_pre_evaluation_other_value AS ov', 'ov.mortgage_id = m.id')
////                ->leftJoin('project_payment_collection AS c', 'c.mortgage_id = m.id')
//                ->leftJoin('project_payment_collection AS c', 'c.project_id = p.id')
//                ->leftJoin('country AS pc', 'pc.id = p.province')
//                ->leftJoin('country AS pcc', 'pcc.id = p.city')
//                ->where(['p.type' => 2])->andWhere(["p.package_id" => $packageid])->orderBy(['p.is_highlights' => SORT_ASC, 'p.id' => SORT_DESC]);
//            $projectListDYArray = new ActiveDataProvider([
//                'query' => $projectListDY,
//                'pagination' => [
//                    'pagesize' => 5
//                ]
//            ]);
            //判断是否发起协同 -- von ------------------------start-----------------------------------
            $dataState = PackageInitiationPlanController::actionGetPackagePlanApiData($packageid);
            $dataState = json_decode($dataState, true);
            $isPlan = $dataState['data']['count'] == 99999 ? true : false;
            $dataC = PackageInitiationPlanController::actionGetPackagePlan($packageid);
            //-----申请过的立项，按钮变灰---start
            $planOld = true;
            $workflow_status = 2;
            $result = 1;
            $UserId = \Yii::$app->user->getId();

            //$applicationModel = (new \yii\db\Query())->from('package_application')->where(['=', 'package_id', $packageid])->andWhere(['=', 'is_package', 1])->andWhere(['=', 'proposer', $UserId])->orderBy('applied_at DESC')->one();
            $applicationModel = (new \yii\db\Query())->from('package_application as pa')->where(['=', 'package_id', $packageid])->andWhere(['=', 'pa.is_package', 1])->andWhere(['=', 'pa.proposer', $UserId])->orderBy('pa.applied_at DESC')->one();
            if (!empty($applicationModel)) {
                $workflow_status = $applicationModel['workflow_status'];
            }
            $packageModel = (new \yii\db\Query())->from('package')->where(['=', 'id', $packageid])->one();
            if (!empty($packageModel)) {
                $result = $packageModel['state'];
            }
            //----申请过的立项，按钮变灰----end
            //所有部门人员
            $userModel = new UserModel();
//            $where = ['not in', 'department',
//                ['总裁办', '风控管理中心', '财务部', '技术部', '', '品牌部', '新大唐学院', '人力行政部',
//                    'ceooffice', 'windControlManagementCenter', 'finance', 'technology', 'brand', 'college', 'humanAdministration', '',
//                ]];
            $where = ['in', 'department', ['project1', 'project2', 'project3', 'project6', 'foreignAffairsOffice']];
            $data['departments'] = $userModel->getDepartmentUsers($where);

            // 判断是否发起协同 -- von ------------------------end-----------------------------------


            //立项评估 --zhao shou qiang------------------start--------------------
            //立项信息  $packageid
            $initation = PackageInitiation::find()->where(['package_id' => $packageid])->one();
            if (empty($initation)) {
                $initation = new PackageInitiation();
            }
            $data['initation'] = $initation;

            //团队组成
            $data['group_users'] = $this->getInitiationGroupUsers($packageid);

            //工作计划
            $data['initation_plan'] = PackageInitiationPlan::getList(['package_id' => $packageid]);

            //团队收益分配
            $data['group_income'] = PackageInitiationIncome::find()->where(['package_id' => $packageid])->all();

            return $this->render('package-detail', ['data' => $data, 'projectListHH' => $projectListHHArray, 'projectListDY' => $projectListDYArray, 'pagesDY' => $pagesDY,
                //'isPlan' => $isPlan, 'dataC' => $dataC, 'workflow_status' => $workflow_status,/*'dataLog' => $dataLog*/]);
                'isPlan' => $isPlan, 'dataC' => $dataC, 'workflow_status' => $workflow_status, 'result' => $result/*'dataLog' => $dataLog*/]);

        }
        return new Exception('访问网页有误');
    }

    /**
     * 资产包日志
     */
    public function actionLog()
    {
        if (Yii::$app->request->isGet && Yii::$app->request->get('packageid')) {
            Yii::$app->session->set('packageid', Yii::$app->request->get('packageid'));
            $packageid = Yii::$app->session->get('packageid');
            // $packageid='1';
            /*show资产包基本信息*/
            $data = Package::find()->where('id=:id', [':id' => $packageid])->asArray()->one();
            if (!$data) {
                return new Exception('该资产包不存在');
            }
            /*获取资产包的更新时间和更新人员*/
            $updateRes = PackageUpdateLog::find()->with('userName')->where(['package_id' => $packageid])->limit(1)->orderBy('id desc')->asArray()->all();
            if ($updateRes) {
                $data['updateTime'] = [$this->timeDiff(strtotime($updateRes[0]['created_at']), time()), $updateRes[0]['userName']['realname']];
            }
            $data['access_users_ids'] = $data['access_users'] != "" ? explode(",", $data['access_users']) : "";

            /*可访问人员名单 */
            $data['access_users'] = $this->getAccessUsers($data['access'], $data['access_users']);
            /*根据资产包状态显示人员*/
            $data['avatar'] = (new Package())->getAvatar($data['state'], $data['owner'], $packageid);
            //是否关注 yt
            $data_like = PackageLike::find()->where(['package_id' => $packageid, 'type' => 1, 'user_id' => Yii::$app->user->id])->asArray()->one();
            if ($data_like['id']) {
                $data['flow'] = 1;
            } else {
                $data['flow'] = 0;
            }

            //判断是否发起协同 -- von ------------------------start-----------------------------------
            $dataState = PackageInitiationPlanController::actionGetPackagePlanApiData($packageid);
            $dataState = json_decode($dataState, true);
            $isPlan = $dataState['data']['count'] == 99999 ? true : false;
            $dataC = PackageInitiationPlanController::actionGetPackagePlan($packageid);
            //-----申请过的立项，按钮变灰---start
            $planOld = true;
            $workflow_status = 2;
            $UserId = \Yii::$app->user->getId();
            //$applicationModel = (new \yii\db\Query())->from('package_application')->where(['=', 'package_id', $packageid])->andWhere(['=', 'is_package', 1])->andWhere(['=', 'proposer', $UserId])->orderBy('applied_at DESC')->one();
            $applicationModel = (new \yii\db\Query())->from('package_application as pa')->where(['=', 'package_id', $packageid])->andWhere(['=', 'pa.is_package', 1])->andWhere(['=', 'pa.proposer', $UserId])->orderBy('pa.applied_at DESC')->one();
            if (!empty($applicationModel)) {
                $workflow_status = $applicationModel['workflow_status'];

            }
            $packageModel = (new \yii\db\Query())->from('package')->where(['=', 'id', $packageid])->one();
            if (!empty($packageModel)) {
                $result = $packageModel['state'];
            }
            //----申请过的立项，按钮变灰----end
            //所有部门人员
            $userModel = new UserModel();
//            $where = ['not in', 'department',
//                ['总裁办', '风控管理中心', '财务部', '技术部', '', '品牌部', '新大唐学院', '人力行政部',
//                    'ceooffice', 'windControlManagementCenter', 'finance', 'technology', 'brand', 'college', 'humanAdministration', '',
//                ]];
            $where = ['in', 'department', ['project1', 'project2', 'project3', 'project6', 'foreignAffairsOffice']];
            $data['departments'] = $userModel->getDepartmentUsers($where);
            // 判断是否发起协同 -- von ------------------------end-----------------------------------


            //资产包日志 --zhao shou qiang------------------start--------------------
            $page = 1;
            //资产包日志
            $packageLog = new PackageLog();
            $packageLogs = $packageLog->getList($packageid);

            //资产包更新日志
            $packageUpdateLog = new PackageUpdateLog();
            $modules = $packageUpdateLog->getModuleArrayTitle();
            $packageUpdateLogUsers = $packageUpdateLog->getUsers($packageid);
            $count = $packageUpdateLog->getCount($packageid, 2, null, null);

            $offset = 10;//默认每页显示条数
            $date = 2;//默认一月内
            $packageUpdateLogs = $packageUpdateLog->getList($packageid, $date, null, null, $offset, ($page - 1) * $offset);

            //分页
            //'totalCount' 为数据总数
            //'pageSize' 为每页显示数
            //'pageSizeParam'=>false, 可将分页路径中per-page参数隐藏去掉
            //'pageParam' => 'p', 可更改分页url中分页参数name名称
            //'route' => false, 当分页在于首页时隐藏掉路由，将/site/index?p=1变为/?p=1
            //'validatePage' => false, 取消分页验证,当手动输入page=20时不再跳到page=1
            $query = PackageUpdateLog::find()->where(['package_id' => $packageid]);
            $countQuery = clone $query;
            $pages = new Pagination(['pageSize' => $offset, 'totalCount' => $countQuery->count()]);
            $linkpager = LinkPager::widget([
                'pagination' => $pages,
                'hideOnSinglePage' => false,
                'maxButtonCount' => 10, //默认显示10页
                'nextPageLabel' => '下一页',
                'prevPageLabel' => '上一页',
                'firstPageLabel' => '首页',
                'lastPageLabel' => '尾页',
                //'options' => ['class' => 'm-pagination'],
            ]);

            $dataLog = array(
                'packageLogs' => $packageLogs,
                'modules' => $modules,
                'packageUpdateLogUsers' => $packageUpdateLogUsers,
                'packageUpdateLogs' => $packageUpdateLogs,
                'count' => $count,
                'linkPager' => $linkpager,
                'page' => $page
            );
            //资产包日志 --zhao shou qiang------------------end-------------------

            //return $this->render('log', ['data' => $data, 'isPlan' => $isPlan, 'dataC' => $dataC, 'dataLog' => $dataLog, 'workflow_status' => $workflow_status]);
            return $this->render('log', ['data' => $data, 'isPlan' => $isPlan, 'dataC' => $dataC, 'dataLog' => $dataLog, 'workflow_status' => $workflow_status, 'result' => $result]);
        }
    }

    /**
     * 资产包立项评估
     */
    public function actionInitiation()
    {
        if (Yii::$app->request->isGet && Yii::$app->request->get('packageid')) {
            Yii::$app->session->set('packageid', Yii::$app->request->get('packageid'));
            $packageid = Yii::$app->session->get('packageid');

            /*show资产包基本信息*/
            $data = Package::find()->where('id=:id', [':id' => $packageid])->asArray()->one();
            if (!$data) {
                return new Exception('该资产包不存在');
            }
            /*获取资产包的更新时间和更新人员*/
            $updateRes = PackageUpdateLog::find()->with('userName')->where(['package_id' => $packageid])->limit(1)->orderBy('id desc')->asArray()->all();
            if ($updateRes) {
                $data['updateTime'] = [$this->timeDiff(strtotime($updateRes[0]['created_at']), time()), $updateRes[0]['userName']['realname']];
            }
            $data['access_users_ids'] = $data['access_users'] != "" ? explode(",", $data['access_users']) : "";
            /*可访问人员名单 */
            // $data['access_users'] = $this->getAccessUsers($data['access'], $data['access_users']);
            /*根据资产包状态显示人员*/
            $data['avatar'] = (new Package())->getAvatar($data['state'], $data['owner'], $packageid);
            //是否关注 yt
            $data_like = PackageLike::find()->where(['package_id' => $packageid, 'type' => 1, 'user_id' => Yii::$app->user->id])->asArray()->one();
            if ($data_like['id']) {
                $data['flow'] = 1;
            } else {
                $data['flow'] = 0;
            }


            //获取自动计算列表
            $data['allCalculate'] = $this->getAllCalculate($packageid);
            //获取省名称
            $countrylist['province'] = (new Country())->getName($data['province']);
            //获取城市名称
            //$countrylist['city'] = (new Country())->getName($data['city']);
            //$data['countrylist'] = $countrylist;
            if ($data['city'] != '') {
                $list = Country::getTitleList();
                $arr = explode(',', $data['city']);
                $array = array();
                if (!empty($arr)) {
                    foreach ($arr as $value) {
                        if ($value > 0) {
                            $array[] = $list[(int)$value];
                        }
                    }
                }
                $countrylist['city'] = join('、', $array);
            } else {
                $countrylist['city'] = '';
            }

            //资产包城市多选
//            $list = Country::getTitleList();
//            $countrylist['city'] = '';
//            $packageCityList = (new Query())
//                ->select(['id', 'city_id'])
//                ->from(PackageCity::tableName())
//                ->where(['package_id'=>(int)$packageid])
//                ->orderBy(['id' => SORT_ASC])
//                ->all();
//            if (!empty($packageCityList)) {
//                $arr = array();
//                foreach ($packageCityList as $value) {
//                    $arr[] = $list[(int)$value['city_id']];
//                }
//                $countrylist['city'] = join('、', $arr);
//            }


            $data['province'] = $countrylist['province'];
            $data['city'] = $countrylist['city'];

            /*show转让信息*/
            $data['transfer'] = (new PackageTransfer())->getTransfer($packageid);
            /*show流转、前置处理记录*/
            $history = PackageTransferHistory::find()->where("package_id=$packageid")->orderBy('order ASC')->asArray()->all();
            $data['history'] = $history;

            //判断是否发起协同 -- von ------------------------start-----------------------------------
            $dataState = PackageInitiationPlanController::actionGetPackagePlanApiData($packageid);
            $dataState = json_decode($dataState, true);
            $isPlan = $dataState['data']['count'] == 99999 ? true : false;
            $dataC = PackageInitiationPlanController::actionGetPackagePlan($packageid);
            //-----申请过的立项，按钮变灰---start
            $planOld = true;
            $workflow_status = 2;
            $UserId = \Yii::$app->user->getId();
            //$applicationModel = (new \yii\db\Query())->from('package_application')->where(['=', 'package_id', $packageid])->andWhere(['=', 'is_package', 1])->andWhere(['=', 'proposer', $UserId])->orderBy('applied_at DESC')->one();
            $applicationModel = (new \yii\db\Query())->from('package_application as pa')->where(['=', 'package_id', $packageid])->andWhere(['=', 'pa.is_package', 1])->andWhere(['=', 'pa.proposer', $UserId])->orderBy('pa.applied_at DESC')->one();
            if (!empty($applicationModel)) {
                $workflow_status = $applicationModel['workflow_status'];

            }
            $packageModel = (new \yii\db\Query())->from('package')->where(['=', 'id', $packageid])->one();
            if (!empty($packageModel)) {
                $result = $packageModel['state'];
            }
            //----申请过的立项，按钮变灰----end
            //所有部门人员
            $userModel = new UserModel();
//            $where = ['not in', 'department',
//                ['总裁办', '风控管理中心', '财务部', '技术部', '品牌部', '新大唐学院', '人力行政部',
//                    'ceooffice', 'windControlManagementCenter', 'finance', 'technology', 'brand', 'college', 'humanAdministration', '',
//                ]];
            $where = ['in', 'department', ['project1', 'project2', 'project3', 'project6', 'foreignAffairsOffice']];
            $data['departments'] = $userModel->getDepartmentUsers($where);
            // 判断是否发起协同 -- von ------------------------end-----------------------------------


            //立项评估 --zhao shou qiang------------------start--------------------
            //立项信息  $packageid
            $initation = PackageInitiation::find()->where(['package_id' => $packageid])->one();
            if (empty($initation)) {
                $initation = new PackageInitiation();
                $initation->package_id = $packageid;
                $initation->save();
            }
            $initation->bargain = $this->set_number_format2($initation->bargain);
            $data['initation'] = $initation;

            //团队组成
            $data['group_users'] = $this->getInitiationGroupUsers($packageid);

            //工作计划
            $data['initation_plan'] = PackageInitiationPlan::getList(['package_id' => $packageid]);

            //团队收益分配
            $data['group_income'] = PackageInitiationIncome::find()->where(['package_id' => $packageid])->all();
            //立项评估 --zhao shou qiang------------------end--------------------

//            $data['principal'] = $this->set_number_format2($data['principal']);
//            $data['interest'] = $this->set_number_format2($data['interest']);

            //return $this->render('initiation', ['data' => $data, 'isPlan' => $isPlan, 'dataC' => $dataC, 'workflow_status' => $workflow_status]);
            return $this->render('initiation', ['data' => $data, 'isPlan' => $isPlan, 'dataC' => $dataC, 'workflow_status' => $workflow_status, 'result' => $result]);
        }
    }

    /**
     *资产包审批反馈
     */
    public function actionAuditFeedback()
    {
        if (Yii::$app->request->isGet && Yii::$app->request->get('packageid')) {
            Yii::$app->session->set('packageid', Yii::$app->request->get('packageid'));
            $packageid = Yii::$app->session->get('packageid');
            // $packageid='1';
            /*show资产包基本信息*/
            $data = Package::find()->where('id=:id', [':id' => $packageid])->asArray()->one();
            if (!$data) {
                return new Exception('该资产包不存在');
            }
            /*获取资产包的更新时间和更新人员*/
            $updateRes = PackageUpdateLog::find()->with('userName')->where(['package_id' => $packageid])->limit(1)->orderBy('id desc')->asArray()->all();
            if ($updateRes) {
                $data['updateTime'] = [$this->timeDiff(strtotime($updateRes[0]['created_at']), time()), $updateRes[0]['userName']['realname']];
            }
            $data['access_users_ids'] = $data['access_users'] != "" ? explode(",", $data['access_users']) : "";

            /*可访问人员名单 */
            // $data['access_users'] = $this->getAccessUsers($data['access'], $data['access_users']);
            /*根据资产包状态显示人员*/
            $data['avatar'] = (new Package())->getAvatar($data['state'], $data['owner'], $packageid);
            //是否关注 yt
            $data_like = PackageLike::find()->where(['package_id' => $packageid, 'type' => 1, 'user_id' => Yii::$app->user->id])->asArray()->one();
            if ($data_like['id']) {
                $data['flow'] = 1;
            } else {
                $data['flow'] = 0;
            }


            //判断是否发起协同 -- von ------------------------start-----------------------------------
            $dataState = PackageInitiationPlanController::actionGetPackagePlanApiData($packageid);
            $dataState = json_decode($dataState, true);
            $isPlan = $dataState['data']['count'] == 99999 ? true : false;
            $dataC = PackageInitiationPlanController::actionGetPackagePlan($packageid);
            //-----申请过的立项，按钮变灰---start
            $planOld = true;
            $workflow_status = 2;
            $UserId = \Yii::$app->user->getId();
            //$applicationModel = (new \yii\db\Query())->from('package_application')->where(['=', 'package_id', $packageid])->andWhere(['=', 'is_package', 1])->andWhere(['=', 'proposer', $UserId])->orderBy('applied_at DESC')->one();
            $applicationModel = (new \yii\db\Query())->from('package_application as pa')->where(['=', 'package_id', $packageid])->andWhere(['=', 'pa.is_package', 1])->andWhere(['=', 'pa.proposer', $UserId])->orderBy('pa.applied_at DESC')->one();
            if (!empty($applicationModel)) {
                $workflow_status = $applicationModel['workflow_status'];

            }
            $packageModel = (new \yii\db\Query())->from('package')->where(['=', 'id', $packageid])->one();
            if (!empty($packageModel)) {
                $result = $packageModel['state'];
            }
            //----申请过的立项，按钮变灰----end
            //所有部门人员
            $userModel = new UserModel();
//            $where = ['not in', 'department',
//                ['总裁办', '风控管理中心', '财务部', '技术部', '品牌部', '新大唐学院', '人力行政部',
//                    'ceooffice', 'windControlManagementCenter', 'finance', 'technology', 'brand', 'college', 'humanAdministration', '',
//                ]];
            $where = ['in', 'department', ['project1', 'project2', 'project3', 'project6', 'foreignAffairsOffice']];
            $data['departments'] = $userModel->getDepartmentUsers($where);
            // 判断是否发起协同 -- von ------------------------end-----------------------------------

            //立项反馈
            $initiationList = $this->getPackageAuditFeedback($packageid, 1);
            //访问反馈
            $accessList = $this->getPackageAuditFeedback($packageid, 5);
            $data['audit']['initiationList'] = $initiationList;
            $data['audit']['accessList'] = $accessList;

            //return $this->render('application', ['data' => $data, 'isPlan' => $isPlan, 'dataC' => $dataC, 'workflow_status' => $workflow_status]);
            return $this->render('application', ['data' => $data, 'isPlan' => $isPlan, 'dataC' => $dataC, 'workflow_status' => $workflow_status, 'result' => $result]);
        }
    }

    /**
     * 资产包审批反馈
     * @param $package_id
     * @return array
     */
    protected function getPackageAuditFeedback($package_id, $type)
    {
        $list = (new \yii\db\Query())->select('*,ar.id as result_id')->from('package_application as pa')
            ->leftJoin('application_result as ar', 'pa.id = ar.application_id')
            ->leftJoin('package as p', 'pa.package_id = p.id')
            //->where(['pa.package_id' => $package_id, 'pa.workflow_status' => 2, 'pa.is_package' => 1, 'pa.type' => $type]) 已审批
            ->where(['pa.package_id' => $package_id, 'pa.is_package' => 1, 'pa.type' => $type])
            ->all();

        if (!empty($list) && is_array($list)) {
            $userModel = new UserModel();
            $userList = $userModel->getDepartmentUsersList();
            foreach ($list as $key => $value) {
                $list[$key]['applied_at'] = date('Y/m/d H:i', strtotime($value['applied_at']));
                //$list[$key]['proposer'] = $userList[$value['proposer']]['description'] . '——' . $userList[$value['proposer']]['realname'];
                //$list[$key]['user_id'] = $userList[$value['user_id']]['description'] . '——' . $userList[$value['user_id']]['realname'];
                $list[$key]['proposer'] = $userList[$value['proposer']]['realname'];
                if (isset($userList[$value['user_id']])) {
                    $list[$key]['user_id'] = $userList[$value['user_id']]['realname'];
                } else {
                    $list[$key]['user_id'] = '暂无';
                }
                $list[$key]['reviewed_at'] = date('Y/m/d H:i:s', strtotime($value['reviewed_at']));
                switch ($value['result']) {
                    case 1:
                        $list[$key]['result'] = '未审核';
                        break;
                    case 2:
                        $list[$key]['result'] = '通过';
                        break;
                    case 3:
                        $list[$key]['result'] = '未通过';
                        break;
                    default;
                }
            }
        }

        return $list;
    }

    /**
     * 尽调报告——团队组成
     * @auth zhao shou qiang
     * @param $package_id
     * @return mixed
     */
    protected function getInitiationGroupUsers($package_id)
    {
        $package = Package::findOne($package_id);
        $initation = PackageInitiation::find()->where(['package_id' => $package_id])->one();

        $data['owner'] = '';
        $data['leader'] = '';
        $data['pre_evaluation'] = '';
        $data['due_diligence'] = '';
        $data['other_team_notes'] = '';

        if (!empty($package) && !empty($initation)) {
            $userModer = new UserModel();
            $departmentUsersList = $userModer->getDepartmentUsersList();
            if (!empty($departmentUsersList)) {
                //上传人
                $owner_id = (int)$package->owner;
                if ($owner_id > 0) {
                    $data['owner'] = $departmentUsersList[$owner_id]['description'] . '-' . $departmentUsersList[$owner_id]['realname'];
                }

                //资产包负责人
                $leader_ids = trim($initation->leader, ',');
                if (strlen($leader_ids) > 0) {
                    $leader_id_arr = explode(',', $leader_ids);
                    $leader = '';
                    foreach ($leader_id_arr as $k_leader) {
                        $leader_id = (int)$k_leader;
                        $leader .= $departmentUsersList[$leader_id]['description'] . '-' . $departmentUsersList[$leader_id]['realname'] . '，';
                    }
                    $data['leader'] = trim($leader, '，');
                }

                //预评估人员
                $pre_evaluation_ids = trim($initation->pre_evaluation, ',');
                if (strlen($pre_evaluation_ids) > 0) {
                    $pre_evaluation_arr = explode(',', $pre_evaluation_ids);
                    $pre_evaluation = '';
                    foreach ($pre_evaluation_arr as $k_pre_evaluation) {
                        $pre_evaluation_id = (int)$k_pre_evaluation;
                        $pre_evaluation .= $departmentUsersList[$pre_evaluation_id]['description'] . '-' . $departmentUsersList[$pre_evaluation_id]['realname'] . '，';
                    }
                    $data['pre_evaluation'] = trim($pre_evaluation, '，');
                }

                //尽调成员
                $due_diligence_ids = trim($initation->due_diligence, ',');
                if (strlen($due_diligence_ids) > 0) {
                    $due_diligence_id_arr = explode(',', $due_diligence_ids);
                    $due_diligence = '';
                    foreach ($due_diligence_id_arr as $k_due_diligence) {
                        $due_diligence_id = (int)$k_due_diligence;
                        $due_diligence .= $departmentUsersList[$due_diligence_id]['description'] . '-' . $departmentUsersList[$due_diligence_id]['realname'] . '，';
                    }
                    $data['due_diligence'] = trim($due_diligence, '，');
                }

                //团队其它说
                $data['other_team_notes'] = $initation->other_team_notes;
            }
        }
        return $data;
    }

    /*资产包详情-基本信息show
    *@ly
    */
    public function actionEditBaseInfo()
    {
        if (Yii::$app->session->get('packageid') && Yii::$app->request->get('o')) {
            $packageid = Yii::$app->session->get('packageid');
            /*show资产包基本信息*/
            $data = Package::find()->where('id=:id', [':id' => $packageid])->asArray()->one();
            /*需要判断下该数据是否被其他人加锁若有他人加锁则无法进入编辑模式
            *及返回 return new Exception('该在资产包有人在编辑');
             * */
            if (!$data) {
                return new Exception('该资产包不存在');
            }
            /*可访问人员名单*/
            $data['access_users'] = $this->getAccessUsers($data['access'], $data['access_users']);
            $list = Country::getTitleList();
            if (strpos($_SERVER["HTTP_REFERER"], 'detail-info') === false) {//判断是来自于完善信息还市编辑详情
                $extendName = 'perfect';
                if (Yii::$app->request->get('o') == 's') {//展示数据
                    //获取省名称
                    $provinceList = (new Country())->getName($data['province']);
                    //获取城市名称
                    //$countryList = (new Country())->getName($data['city']);

                    //资产包城市多选
//                    $countryList = '';
//                    $packageCityList = (new Query())
//                        ->select(['id', 'city_id'])
//                        ->from(PackageCity::tableName())
//                        ->where(['package_id'=>(int)$packageid])
//                        ->orderBy(['id' => SORT_ASC])
//                        ->all();
//                    if (!empty($packageCityList)) {
//                        $arr = array();
//                        foreach ($packageCityList as $value) {
//                            $arr[] = $list[(int)$value['city_id']];
//                        }
//                        $countryList = join('、', $arr);
//                    }


                    if ($data['city'] != '') {
                        $arr = explode(',', $data['city']);
                        $list = Country::getTitleList();
                        $array = array();
                        if (!empty($arr) && is_array($arr)) {
                            foreach ($arr as $value) {
                                if ($value > 0) {
                                    $array[] = $list[(int)$value];
                                }
                            }
                        }
                        $countryList = join('、', $array);
                    } else {
                        $countryList = '';
                    }

                    $data['countrylist'] = array('province' => $provinceList, 'city' => $countryList);
                    $extendName = 'show-base-' . $extendName;
                    return $this->renderPartial($extendName, ['data' => $data, 'editFlag' => TRUE]);
                } else {//编辑
                    $provinceList = Country::find()->where("pid=0")->asArray()->all();
                    $countryList = Country::find()->where("pid=" . $data['province'])->asArray()->all();
                    $data['countrylist'] = array('province' => $provinceList, 'city' => $countryList);
                    $extendName = 'edit-base-' . $extendName;
                    return $this->renderPartial($extendName, ['data' => $data, 'editFlag' => TRUE]);
                }
            } else {//若是资产包详情   需要输出自动计算模块及添加锁
                $extendName = 'detail';
                $data['allCalculate'] = $this->getAllCalculate($packageid);
                if (Yii::$app->request->get('o') == 's') {//展示数据
                    $lock = $this->getUnLock(Package::tableName(), 'id', $packageid);
                    if ($lock[0]) {
                        //获取省名称
                        $provinceList = (new Country())->getName($data['province']);
                        //获取城市名称
                        //$countryList = (new Country())->getName($data['city']);

                        //资产包城市多选
//                        $countryList = '';
//                        $packageCityList = (new Query())
//                            ->select(['id', 'city_id'])
//                            ->from(PackageCity::tableName())
//                            ->where(['package_id'=>(int)$packageid])
//                            ->orderBy(['id' => SORT_ASC])
//                            ->all();
//                        if (!empty($packageCityList)) {
//                            $arr = array();
//                            foreach ($packageCityList as $value) {
//                                $arr[] = $list[(int)$value['city_id']];
//                            }
//                            $countryList = join('、', $arr);
//                        }


                        if ($data['city'] != '') {
                            $arr = explode(',', $data['city']);
                            $list = Country::getTitleList();
                            $array = array();
                            if (!empty($arr) && is_array($arr)) {
                                foreach ($arr as $value) {
                                    if ($value > 0) {
                                        $array[] = $list[(int)$value];
                                    }
                                }
                            }
                            $countryList = join('、', $array);
                        } else {
                            $countryList = '';
                        }

                        $data['countrylist'] = array('province' => $provinceList, 'city' => $countryList);
                        $extendName = 'show-base-' . $extendName;
                        return $this->renderPartial($extendName, ['data' => $data, 'editFlag' => TRUE]);
                    } else {
                        //return json_encode(Responses::response400($lock[1], true));
                        return $lock[1];
                    }
                } else {//编辑
                    $lock = $this->getLock(Package::tableName(), 'id', $packageid);
                    if ($lock[0]) {
                        $provinceList = Country::find()->where("pid=0")->asArray()->all();
                        $countryList = array();
                        if ($data['province'] > 0) {
                            $countryList = Country::find()->where("pid=" . $data['province'])->asArray()->all();
                        }
                        $data['countrylist'] = array('province' => $provinceList, 'city' => $countryList);
                        $extendName = 'edit-base-' . $extendName;
                        return $this->renderPartial($extendName, ['data' => $data, 'editFlag' => TRUE]);
                    } else {
//                        return json_encode(Responses::response400($lock[1], true));
                        return $lock[1];
                    }
                }
            }
        }
        return new Exception('访问有误！');
    }

    /**
     * 资产包立项信息
     * @auth zhao shou qiang
     * @return string
     */
    public function actionInitationBaseInfo()
    {
        if (Yii::$app->request->isAjax) {
            $package_id = (int)Yii::$app->request->get('package_id');
            $type = (int)Yii::$app->request->get('type', 1); //1读， 2修改
            $userId = Yii::$app->user->id;
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            //只读页面
            if ($type === 2) {
                $data = Package::find()->where('id=:id', [':id' => $package_id])->asArray()->one();
                if ($data === null) {
                    return Responses::response400('该资产包不存在', true);
                }
                //判断是否加锁
                $isLockedData = $this->is_locked(Package::findOne($package_id), $userId);
                if (!$isLockedData['state']) {
                    return Responses::response400($isLockedData['msg'], true);
                }
                //获取省市列表
                $query = new Query();
                $provinceList = $query->select([])->from('country')->where(['pid' => 0])->indexBy('id')->all();
                $cityList = array();
                if ($data['province'] > 0) {
                    $cityList = $query->select([])->from('country')->where(['pid' => $data['province']])->indexBy('id')->all();
                }
                $countryList['province'] = $provinceList;
                $countryList['city'] = $cityList;
                $data['principal'] = $this->set_number_format2($data['principal']);
                $data['interest'] = $this->set_number_format2($data['interest']);
                $data['hushu'] = (int)$data['hushu'];

                //加锁
                $package = Package::findOne((int)$package_id);
                $package->hushu = (int)$package->hushu;
                $lockData = $this->locking($package, $userId);
                if (!$lockData['state']) {
                    return Responses::response400($lockData['msg'], true);
                }

                $str = $this->renderPartial('@app/views/package/investigation/base-info-edit.php', ['data' => $data, 'countryList' => $countryList]);
                return Responses::response200($str, 1, '切换成功');

                //编辑页面
            } elseif ($type === 1) {
                $post = Yii::$app->request->post();
                $model = Package::findOne($package_id);
                if ($model === null) {
                    return Responses::response400('该资产包不存在', true);
                }
                //判断是否加锁
                $model->hushu = (int)$model->hushu;
                $isLockedData = $this->is_locked($model, $userId);
                if (!$isLockedData['state']) {
                    return Responses::response400($isLockedData['msg'], true);
                }

                $transaction = Yii::$app->db->beginTransaction();
                try {
                    //编辑资产包
                    if ($post['Package']['principal'] != '') {
                        if (!is_numeric($post['Package']['principal'])) {
                            $post['Package']['principal'] = $this->set_number_format($post['Package']['principal']);
                        }
                    } else {
                        $post['Package']['principal'] = '0';
                    }

                    if ($post['Package']['interest'] != '') {
                        if (!is_numeric($post['Package']['interest'])) {
                            $post['Package']['interest'] = $this->set_number_format($post['Package']['interest']);
                        }
                    } else {
                        $post['Package']['interest'] = '0';
                    }

                    /*if ($post['Package']['hushu'] != '') {
                        if (!is_numeric($post['Package']['hushu'])) {
                            $post['Package']['hushu'] = $this->set_number_format($post['Package']['hushu']);
                        }
                    } else {
                        $post['Package']['hushu'] = '0';
                    }*/
                    $post['Package']['hushu'] = (int)$post['Package']['hushu'];

                    //$cityData = array();
                    if (isset($post['Package']['city']) && isset($post['Package']['city']) != '') {
                        //$cityData =  $post['Package']['city'];
                        foreach ($post['Package']['city'] as $key => $value) {
                            if ($value == 0) {
                                unset($post['Package']['city'][$key]);
                            }
                        }
                        $post['Package']['city'] = join(',', $post['Package']['city']);
                    } else {
                        $post['Package']['city'] = '';
                    }

                    //TODO 添加记录
                    $packageModel = new Package();
                    $res = $packageModel->setUpdateLog($package_id, $post['Package'], $userId, PackageUpdateLog::MODULE_SUBJECT);
                    if (!$res['state']) {
                        throw new \Exception($res['msg']);
                    }

                    $post['Package']['lock_user'] = null;
                    $post['Package']['lock_timestamp'] = null;

                    if ($model->load($post) && $model->save()) {
                        //删除原来的记录，添加新记录
//                        $packageCityList = PackageCity::find()->where(['package_id'=>$package_id])->all();
//                        if (!empty($packageCityList)) {
//                            foreach ($packageCityList as $value) {
//                                $res = $value->delete();
//                                if (!$res) {
//                                    throw new \Exception($res['保存失败']);
//                                }
//                            }
//                        }
//
//                        if (!empty($cityData)) {
//                            $model = new PackageCity();
//                            foreach ($cityData as $value) {
//                                $_model = clone $model;
//                                $_model->package_id = $package_id;
//                                $_model->city_id = (int)$value;
//                                $_model->created_at = date('Y-m-d H:i:s');
//                                $res = $_model->save();
//                                if (!$res) {
//                                    throw new \Exception($res['保存失败']);
//                                }
//                            }
//                        }


                        $transaction->commit();

                        $data = Package::find()->where('id=:id', [':id' => $package_id])->asArray()->one();
                        $country = Country::getTitleList();
                        if ($data['province'] > 0) {
                            $data['province'] = $country[(int)$data['province']];
                        }
                        /*if ($data['city'] > 0) {
                            $data['city'] = $country[(int)$data['city']];
                        }*/

//                        $data['city'] = '';
//                        $packageCityList = (new \yii\db\Query())
//                            ->select(['id', 'city_id'])
//                            ->from(\common\models\PackageCity::tableName())
//                            ->where(['package_id'=>(int)$data['id']])
//                            ->orderBy(['id' => SORT_ASC])
//                            ->all();
//                        if (!empty($packageCityList)) {
//                            $list = Country::getTitleList();
//                            $array = array();
//                            foreach ($packageCityList as $value) {
//                                $array[] = $list[(int)$value['city_id']];
//                            }
//                            $data['city'] = join('、', $array);
//                        }

                        if ($data['city'] != '') {
                            $arr = explode(',', $data['city']);
                            $array = array();
                            $list = Country::getTitleList();
                            foreach ($arr as $value) {
                                if ($value > 0) {
                                    $array[] = $list[(int)$value];
                                }
                            }
                            $data['city'] = join('、', $array);
                        }

                        $data['principal'] = $this->set_number_format2($data['principal']);
                        $data['interest'] = $this->set_number_format2($data['interest']);
                        //$data['hushu'] = $this->set_number_format2($data['hushu']);
                        $data['hushu'] = (int)$data['hushu'];

                        $data['allCalculate'] = $this->getAllCalculate($package_id);

                        //获取省名称
                        $countrylist['province'] = (new Country())->getName($data['province']);
                        //获取城市名称
                        $countrylist['city'] = (new Country())->getName($data['city']);

                        $str = $this->renderPartial('@app/views/package/investigation/base-info.php', ['data' => $data]);
                        $messageState = self::actionPostMessage($package_id);
                        if (!empty($messageState) && $messageState['code'] == 200) {
                            return Responses::response200($str, 1, '保存成功');
                        } else {
                            throw new \Exception('保存成功,消息发送失败');
                        }
                    } else {
                        $error = $model->getFirstErrors();
                        $message = '';
                        if (!empty($error)) {
                            foreach ($error as $value) {
                                $message .= $value;
                            }
                            $tmpStr = strip_tags($message);
                            $tmpLen = mb_strlen($tmpStr);
                            $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                        }
                        throw new \Exception($message);
                    }

                } catch (\Exception $e) {
                    $transaction->rollBack();
                    $message = $e->getMessage();
                    return Responses::response400($message, true);
                } catch (\Throwable $e) {
                    $transaction->rollBack();
                    $message = $e->getMessage();
                    return Responses::response400($message, true);
                }

                //取消页面
            } elseif ($type === 3) {
                $data = Package::find()->where('id=:id', [':id' => $package_id])->asArray()->one();
                if (!$data) {
                    return Responses::response400('该资产包不存在', true);
                }

                //解锁
                $package = Package::findOne((int)$package_id);
                $package->hushu = (int)$package->hushu;
                $unlockindData = $this->unlocking($package, $userId);
                if (!$unlockindData['state']) {
                    return Responses::response400($unlockindData['msg'], true);
                }

                $country = Country::getTitleList();
                if ($data['province'] > 0) {
                    $data['province'] = $country[(int)$data['province']];
                }
                /*if ($data['city'] > 0) {
                    $data['city'] = $country[(int)$data['city']];
                }*/
                $data['principal'] = $this->set_number_format2($data['principal']);
                $data['interest'] = $this->set_number_format2($data['interest']);
                //$data['hushu'] = $this->set_number_format2($data['hushu']);
                $data['hushu'] = (int)$data['hushu'];

//                $data['city'] = '';
//                $packageCityList = (new \yii\db\Query())
//                    ->select(['id', 'city_id'])
//                    ->from(\common\models\PackageCity::tableName())
//                    ->where(['package_id'=>(int)$data['id']])
//                    ->orderBy(['id' => SORT_ASC])
//                    ->all();
//                if (!empty($packageCityList)) {
//                    $list = Country::getTitleList();
//                    $array = array();
//                    foreach ($packageCityList as $value) {
//                        $array[] = $list[(int)$value['city_id']];
//                    }
//                    $data['city'] = join('、', $array);
//                }

                if ($data['city'] != '') {
                    $list = Country::getTitleList();
                    $arr = explode(',', $data['city']);
                    $array = array();
                    if (!empty($arr)) {
                        foreach ($arr as $value) {
                            $array[] = $list[(int)$value];
                        }
                    }
                    $data['city'] = join('、', $array);
                } else {
                    $data['city'] = '';
                }

                $data['allCalculate'] = $this->getAllCalculate($package_id);
                $str = $this->renderPartial('@app/views/package/investigation/base-info.php', ['data' => $data]);
                return Responses::response200($str, 1, '切换成功');
            }
        }
    }

    /*
     * 获取自动计算模块
     *   * @ly
     */
    public static function getAllCalculate($package_id)
    {//$package_id
        $allList = Package::find()->with('initiation', 'project')->where('id=:id', [':id' => $package_id])->asArray()->one();
        $backArray = array();
        if ($allList['project']) {
            $principalDY = 0;//抵押类总本金
            $countDY = 0;//抵押项目个数
            $huixianBS = 0;//回现保守
            $huixianJJ = 0;//回现激进
            $principalYS = 0;//已诉类总本金
            $countYS = 0;//已诉项目个数
            $principalXC = 0;//续存类总本金
            $countXC = 0;//续存项目个数
            $principalPC = 0;//破产类总本金
            $countPC = 0;//破产项目个数
            $principalLD = 0;//亮点类总本金
            $countLD = 0;//亮点项目个数
            $countGQ = 0;//国企项目个数
            foreach ($allList['project'] as $val) {
                if ($val['type2'] == 2) {//汇总抵押类
                    //抵押类的项目本金
                    $principalDY += (float)$val['principal'];
                    //抵押类项目个数
                    $countDY++;
                }
                if ($val['type'] == 2) {//汇总抵押列表
                    //project_payment_collection抵押类项目预评估(payment_reservation回现保守)(payment_radical回现激进)
                    $res = ProjectPaymentCollection::find()->where('project_id=:project_id', [':project_id' => $val['id']])->asArray()->one();
//                    echo '抵押-'.$val['id'].'<br/>';
//                    var_dump($res);
                    if ($res) {
                        $huixianBS += (float)$res['payment_reservation'];
                        $huixianJJ += (float)$res['payment_radical'];
                    }
                } else {
//                    echo '混合-'.$val['id'].'<br/>';
//                    var_dump($res);
                    //project_pre_evaluation_value_evaluation（保证、混合类项目预评估）价值评估(conservation保守回收预估值) (radical激进回收预估值)
                    $res = ProjectPreEvaluationValueEvaluation::find()->where('project_id=:project_id', [':project_id' => $val['id']])->asArray()->one();
                    if ($res) {
                        $huixianBS += (float)$res['conservation'];
                        $huixianJJ += (float)$res['radical'];
                    }
                }
                if ($val['is_suit'] == 1) {//已诉类
                    //已诉类的项目本金
                    $principalYS += (float)$val['principal'];
                    //已诉类项目个数
                    $countYS++;
                }
                if ($val['management_status'] == 1) {//续存类
                    //续存类的项目本金
                    $principalXC += (float)$val['principal'];
                    //续存类项目个数
                    $countXC++;
                } elseif ($val['management_status'] == 4) {//破产类
                    //破产类的项目本金
                    $principalPC += (float)$val['principal'];
                    //破产类项目个数
                    $countPC++;
                }
                if ($val['is_highlights'] == 1) {//亮点类
                    //亮点类的项目本金
                    $principalLD += (float)$val['principal'];
                    //亮点类项目个数
                    $countLD++;
                }
                if ($val['enterprise'] == 1) {//国企类
                    $countGQ++;
                }
            }
            //开始计算所需的结果
            $principal = (float)$allList['principal'];
            $hushu = (float)$allList['hushu'];
            //抵押类
            $backArray['principalDY'] = round($principalDY, 2);
            $backArray['principalDYB'] = $principal == 0 ? 0 : round(($principalDY / $principal * 100), 2) . '%';
            $backArray['countDY'] = $countDY;
            $backArray['countDYB'] = $hushu == 0 ? 0 : round(($countDY / $hushu * 100), 2) . '%';
            //已诉
            $backArray['principalYS'] = round($principalYS, 2);
            $backArray['principalYSB'] = $principal == 0 ? 0 : round(($principalYS / $principal * 100), 2) . '%';
            $backArray['countYS'] = $countYS;
            $backArray['countYSB'] = $hushu == 0 ? 0 : round(($countYS / $hushu * 100), 2) . '%';
            //存续
            $backArray['principalXC'] = round($principalXC, 2);
            $backArray['principalXCB'] = $principal == 0 ? 0 : round(($principalXC / $principal * 100), 2) . '%';
            $backArray['countXC'] = $countXC;
            $backArray['countXCB'] = $hushu == 0 ? 0 : round(($countXC / $hushu * 100), 2) . '%';
            //破产
            $backArray['principalPC'] = round($principalPC, 2);
            $backArray['principalPCB'] = $principal == 0 ? 0 : round(($principalPC / $principal * 100), 2) . '%';
            $backArray['countPC'] = $countPC;
            $backArray['countPCB'] = $hushu == 0 ? 0 : round(($countPC / $hushu * 100), 2) . '%';
            //亮点
            $backArray['principalLD'] = round($principalLD, 2);
            $backArray['principalLDB'] = $principal == 0 ? 0 : round(($principalLD / $principal * 100), 2) . '%';
            $backArray['countLD'] = $countLD;
            $backArray['countLDB'] = $hushu == 0 ? 0 : round(($countLD / $hushu * 100), 2) . '%';
            //折扣率 当前卖方报价/本金
            $backArray['zkl'] = 0;
            $backArray['evaluationHBB'] = '--';
            if ($allList['initiation']) {
                $bargain = (float)$allList['initiation']['bargain'];
                //折扣率
                $backArray['zkl'] = $principal == 0 ? 0 : round(($bargain / $principal * 100), 2) . '%';
                //预估投资回报率====保守投资回报率（项目回现保守总和/当前卖方报价）~激进投资回报率（项目回现激进总和/当前卖方报价$huixianBS $huixianJJ
                if ($bargain > 0) {
                    $backArray['evaluationHBB'] = round(($huixianBS / $bargain * 100), 2) . '%~' . round(($huixianJJ / $bargain * 100), 2) . '%';
                } else {
                    $backArray['evaluationHBB'] = '--';
                }
            }
            //企业国企
            $backArray['countGQ'] = $countGQ;
            $backArray['countGQB'] = $hushu == 0 ? 0 : round(($countGQ / $hushu * 100), 2) . '%';
        }
        return $backArray;

    }


    /**
     * 获取转让记录的信息show
     * @ly
     */
    public function actionEditTransferInfo()
    {
        if (Yii::$app->session->get('packageid') && Yii::$app->request->get('o')) {
            $packageid = Yii::$app->session->get('packageid');
            $data['transfer'] = (new PackageTransfer())->getTransfer($packageid);
            if (strpos($_SERVER["HTTP_REFERER"], 'detail-info') === false) {//判断是来自于完善信息还市编辑详情
                if (Yii::$app->request->get('o') == 's') {//展示数据
                    return $this->renderPartial('show-transfer-detail', ['data' => $data, 'editFlag' => TRUE]);
                } else {//编辑
                    return $this->renderPartial('edit-transfer-detail', ['data' => $data, 'editFlag' => TRUE]);
                }
            } else {//资产包详情 需要加锁的判断
                if (Yii::$app->request->get('o') == 's') {//展示数据
                    $lock = $this->getUnLock(PackageTransfer::tableName(), 'package_id', $packageid);
                    if ($lock[0]) {
                        return $this->renderPartial('show-transfer-detail', ['data' => $data, 'editFlag' => TRUE]);
                    } else {
                        // return json_encode(Responses::response400($lock[1], true));
                        return $lock[1];
                    }
                } else {//编辑
                    $lock = $this->getLock(PackageTransfer::tableName(), 'package_id', $packageid);
                    if ($lock[0]) {
                        return $this->renderPartial('edit-transfer-detail', ['data' => $data, 'editFlag' => TRUE]);
                    } else {
                        //return json_encode(Responses::response400($lock[1], true));
                        return $lock[1];
                    }
                }
            }

        }
        return new Exception('访问有误！');
    }

    /*
     * 前期流转记录show
     * */
    public function actionEditHistoryInfo()
    {
        if (Yii::$app->session->get('packageid') && Yii::$app->request->get('o')) {
            $packageid = Yii::$app->session->get('packageid');
            $data['history'] = PackageTransferHistory::find()->where("package_id=$packageid")->orderBy('order ASC')->asArray()->all();
            if (strpos($_SERVER["HTTP_REFERER"], 'detail-info') === false) {//判断是来自于完善信息还市编辑详情
                if (Yii::$app->request->get('o') == 's') {//展示数据
                    return $this->renderPartial('show-history-detail', ['data' => $data, 'editFlag' => TRUE]);
                } else {//编辑
                    return $this->renderPartial('edit-history-detail', ['data' => $data, 'editFlag' => TRUE]);
                }
            } else {//资产包详情 添加锁
                if (Yii::$app->request->get('o') == 's') {//展示数据
                    return $this->renderPartial('show-history-detail', ['data' => $data, 'editFlag' => TRUE]);
//                    $lock = $this->getUnLock(PackageTransferHistory::tableName(), 'package_id', $packageid);
//                    if ($lock[0]) {
//                       return $this->renderPartial('show-history-detail', ['data' => $data, 'editFlag' => TRUE]);
//                    } else {
//                        //return json_encode(Responses::response400($lock[1], true));
//                        return $lock[1];
//                    }
                } else {//编辑
                    return $this->renderPartial('edit-history-detail', ['data' => $data, 'editFlag' => TRUE]);
//                    $lock = $this->getLock(PackageTransferHistory::tableName(), 'package_id', $packageid);
//                    if ($lock[0]) {
//                        return $this->renderPartial('edit-history-detail', ['data' => $data, 'editFlag' => TRUE]);
//                    } else {
//                        // return json_encode(Responses::response400($lock[1], true));
//                        return $lock[1];
//                    }
                }
            }
        }
        return new Exception('访问有误！');
    }

    /**分页-异步请求项目列表（混合类和保证类）
     * @ly
     * @return string*
     */
    public function actionProjectHH()
    {
        if (Yii::$app->request->isAjax && Yii::$app->session->get('packageid')) {
            $is_highlights = '';
            $packageid = Yii::$app->session->get('packageid');
            $tabID = Yii::$app->request->get('tabID', 1);
            $projectListHH = Project::find()->with('provinceName', 'cityName', 'lawsuit', 'evaluation', 'note')->where(['<>', 'type', 2])->andWhere("package_id=$packageid");//->orderBy(['is_highlights'=>SORT_ASC,'id'=>SORT_DESC]);
            if (Yii::$app->request->isGet) {//高级筛选
                $getData = Yii::$app->request->get();
                //关键词
                if (isset($getData['keyWords']))
                    $projectListHH->andFilterWhere(['like', 'title', $getData['keyWords']]);
                //省
                if (isset($getData['province']))
                    $projectListHH->andFilterWhere(['=', 'province', $getData['province']]);
                //诉讼状态
                if (isset($getData['is_suit']))
                    $projectListHH->andFilterWhere(['in', 'is_suit', $getData['is_suit']]);//implode(',',$getData['is_suit'])
                //借款人状况
                if (isset($getData['management_status']))
                    $projectListHH->andFilterWhere(['in', 'management_status', $getData['management_status']]);
                //抵押物类型
                if (isset($getData['mortgage_type']) && count($getData['mortgage_type']) > 0) {
                    $sqlStr[] = 'or';
                    //['and', 'type=1', ['or', 'id=1', 'id=2']]
                    foreach ($getData['mortgage_type'] as $mortgageTypeValue) {
                        $sqlStr[] = 'mortgage_type like "%' . $mortgageTypeValue . '%"';
                        //$projectListHH->andFilterWhere(['or',['like','mortgage_type',$mortgageTypeValue],);
                    }
                    $projectListHH->andFilterWhere($sqlStr);
                }
                if (isset($getData['is_highlights']))
                    $projectListHH->andFilterWhere(['=', 'is_highlights', $getData['is_highlights']]);
                $is_highlights = Yii::$app->request->get('is_highlights');
                if (!isset($getData['sort']))//当无 sort 时 使用默认排序
                    $projectListHH->orderBy(['is_highlights' => SORT_ASC, 'id' => SORT_DESC]);
            }
            $pageSize = Yii::$app->request->get('per-page-hh', 10);//默认显示条数
            /* if (Yii::$app->request->isPost && !empty(Yii::$app->request->post())) {//添加高级查询
                $postData = Yii::$app->request->post();
                $is_highlights = Yii::$app->request->post('is_highlights');
                //添加借款人关键词查询
                $keyWords = Yii::$app->request->post('keyWords');
                $projectListHH->andFilterWhere(['like','title',$keyWords]);
                unset($postData['keyWords']);
                $projectListHH->andFilterWhere($postData);
//               echo  $projectListHH->createCommand()->getRawSql();
//               exit;
            }*/
            $projectListHHArray = new ActiveDataProvider([
                'query' => $projectListHH,
                'pagination' => [
                    'pagesize' => $pageSize
                ]
            ]);
            return $this->renderPartial('show-detail-project-hh', ['projectListHH' => $projectListHHArray, 'tabID' => $tabID, 'is_highlights' => $is_highlights]);
        }
        return '';
    }

    /**分页 异步请求项目列表（抵押类）
     * @ly
     * @return string*
     */
    public function actionProjectDY()
    {
        if (Yii::$app->request->isAjax) {
            $packageid = Yii::$app->session->get('packageid');
            $tabID = Yii::$app->request->get('tabID', 1);
            $is_highlights = '';


//            $projectListDY = (new \yii\db\Query())
//                ->from('project AS p')
//                ->select('
//                p.package_id,p.id,p.borrower,p.principal,p.interest,p.is_suit,p.management_status,p.enterprise,p.industry,p.guarantor,p.guarantor_status,p.mortgage_details,p.is_highlights,pc.title as pctitle,pcc.title as pcctitle,
//                l.judgement,l.execution,l.court,l.block,
//                m.mortgage_principal,m.mortgage_interest,s.mortgage_type,s.mortgage_owner,s.mortgage_code,s.mortgage_building_area,s.mortgage_land_area,s.maximum_mortgage,s.remaining_service_life,
//                s.is_first_mortgage,s.mortgage_future,s.mortgage_seal_order,s.is_first_seal,s.mortgage_seal_state,s.mortgage_order,s.mortgage_situation,
//                v.payment_reservation as vpayment_reservation,v.payment_radical as vpayment_radical,v.price_reason,
//                ov.bought_analysis,ov.bought_reservation,ov.bought_radical,s.mortgage_other_seal_order,s.mortgage_other_seal_state,
//                c.payment_reservation,c.payment_radical,c.payment_tax,c.payment_month,c.payment_analysis
//                ')
//                ->leftJoin('project_pre_evaluation_mortgage AS m', 'm.project_id = p.id')
//                ->leftJoin('project_pre_evaluation_seal as s', 's.mortgage_id=m.id')
//                ->leftJoin('project_pre_evaluation_lawsuit AS l', 'l.project_id = p.id')
////                ->leftJoin('project_pre_evaluation_value AS v', 'v.mortgage_id = m.id')
//                ->leftJoin('project_pre_evaluation_value AS v', 'v.ppes = s.id')
//                ->leftJoin('project_pre_evaluation_other_value AS ov', 'ov.project_id = p.id')
////                ->leftJoin('project_pre_evaluation_other_value AS ov', 'ov.mortgage_id = m.id')
////                ->leftJoin('project_payment_collection AS c', 'c.mortgage_id = m.id')
//                ->leftJoin('project_payment_collection AS c', 'c.project_id = p.id')
//                ->leftJoin('country AS pc', 'pc.id = p.province')
//                ->leftJoin('country AS pcc', 'pcc.id = p.city')
//                ->where(['p.type' => 2])->andWhere(["p.package_id" => $packageid])->orderBy(['p.is_highlights' => SORT_ASC, 'p.id' => SORT_DESC]);
            $projectListDY = Project::find()->with('provinceName', 'cityName', 'lawsuit', 'mortgage.seal.value', 'oValue', 'payment')->where(['type' => 2])->andWhere(["package_id" => $packageid]);
            if (Yii::$app->request->isGet) {//高级筛选
                $getData = Yii::$app->request->get();
                //关键词
                if (isset($getData['keyWords']))
                    $projectListDY->andFilterWhere(['like', 'title', $getData['keyWords']]);
                //省
                if (isset($getData['province']))
                    $projectListDY->andFilterWhere(['=', 'province', $getData['province']]);
                //诉讼状态
                if (isset($getData['is_suit']))
                    $projectListDY->andFilterWhere(['in', 'is_suit', $getData['is_suit']]);//implode(',',$getData['is_suit'])
                //借款人状况
                if (isset($getData['management_status']))
                    $projectListDY->andFilterWhere(['in', 'management_status', $getData['management_status']]);
                //抵押物类型
                if (isset($getData['mortgage_type']) && count($getData['mortgage_type']) > 0) {
                    $sqlStr[] = 'or';
                    //['and', 'type=1', ['or', 'id=1', 'id=2']]
                    foreach ($getData['mortgage_type'] as $mortgageTypeValue) {
                        $sqlStr[] = 'mortgage_type like "%' . $mortgageTypeValue . '%"';
                        //$projectListHH->andFilterWhere(['or',['like','mortgage_type',$mortgageTypeValue],);
                    }
                    $projectListDY->andFilterWhere($sqlStr);
                }
                if (isset($getData['is_highlights']))
                    $projectListDY->andFilterWhere(['=', 'is_highlights', $getData['is_highlights']]);
                $is_highlights = Yii::$app->request->get('is_highlights');
            }
            $pageSize = Yii::$app->request->get('per-page-dy', 10);//默认显示条数
            /* if (Yii::$app->request->isPost && !empty(Yii::$app->request->post())) {//添加高级查询mortgage_code
                $postData = Yii::$app->request->post();
                $is_highlights = Yii::$app->request->post('is_highlights');
                //添加借款人关键词查询
                $keyWords = Yii::$app->request->post('keyWords');
                $projectListDY->andFilterWhere(['like','title',$keyWords]);
                unset($postData['keyWords']);
                $projectListDY->andFilterWhere($postData);
            }*/
            $projectListDY->orderBy(['is_highlights' => SORT_ASC, 'id' => SORT_DESC]);
            $pagesDY = new Pagination(['totalCount' => $projectListDY->count(), 'pageSize' => $pageSize]);    //$pageSize实例化分页类,带上参数(总条数,每页显示条数)
            $projectListDYArray = $projectListDY->offset($pagesDY->offset)->limit($pagesDY->limit)->asArray()->all();
//            $projectListDYArray = new ActiveDataProvider([
//                'query' => $projectListDY,
//                'pagination' => [
//                    'pagesize' => 5
//                ]
//            ]);
            return $this->renderPartial('show-detail-project-dy', ['projectListDY' => $projectListDYArray, 'pagesDY' => $pagesDY, 'tabID' => $tabID, 'is_highlights' => $is_highlights]);
        }
        return '';
    }

    /**
     *资产包基本信息提交编辑信息接口
     * @auth ly
     * title  type creditorname province city principal principal_range hushu detail
     * 传值package_id或是session 传值
     */
    public function actionEidtBase()
    {
        $data = Responses::response404('保存失败');//资产包基本信息更新
        if (Yii::$app->request->isPost) {
            $userId = Yii::$app->user->id;
            $postdata = Yii::$app->request->post();
            $packageid = Yii::$app->session->get('packageid');
            //$packageid='1';province:4city:55
            /*根据$packageid获取原有资产包的基本信息*/
            $oldinfo = Package::find()->where("id=$packageid")->asArray()->one();
            //&& !empty($postdata['creditor'])


            if (isset($postdata['city']) && !empty($postdata['city'])) {
                //$cityData = $postdata['city'];
                foreach ($postdata['city'] as $key => $value) {
                    if ($value == 0) {
                        unset($postdata['city'][$key]);
                    }
                }
                $postdata['city'] = join(',', $postdata['city']);
            } else {
                //$cityData = array();
                $postdata['city'] = '';
            }

            if (!empty($postdata) && $postdata['province'] > 0 && /*$postdata['city']>0 &&*/
                (is_numeric($postdata['principal']) || empty($postdata['principal'])) && (is_numeric($postdata['interest']) || empty($postdata['interest'])) && is_numeric($postdata['hushu'])
            ) {
                $difFlag = 1;
                foreach ($postdata as $key => $val) {
                    if ($oldinfo[$key] != $val) {
                        //unset($postdata[$key]);
                        $difFlag = 0;
                        break;
                    }
                }
                if ($difFlag) {
                    return json_encode(Responses::response200('', 0, '保存成功'));//资产包基本信息
                }
                //1、100万以下，2、100-1000万，3、1000-5000万，4、5000万-1亿，5、1亿以上
                $postdata['principal'] = str_replace(',', '', $postdata['principal']);
                $principal = floatval($postdata['principal']);
                switch ($principal) {
                    case $principal >= 100000000:
                        $postdata['principal_range'] = 5;
                        break;
                    case $principal >= 50000000 && $principal < 100000000:
                        $postdata['principal_range'] = 4;
                        break;
                    case $principal >= 10000000 && $principal < 50000000:
                        $postdata['principal_range'] = 3;
                        break;
                    case $principal >= 1000000 && $principal < 10000000:
                        $postdata['principal_range'] = 2;
                        break;
                    case $principal < 1000000:
                        $postdata['principal_range'] = 1;
                        break;
                }
                $postdata['updated_at'] = date('Y-m-d H:i:s');
                /*通过获取的新数据与 原有数据对比获取到更新的数据在入库*/
                //$res = Yii::$app->db->createCommand()->update(Package::tableName(), $postdata, "id=$packageid")->execute();
                //if ($res) {//更新成功
                //    $data = Responses::response200('', 0, '资产包基本信息更新成功');
                //}

                //添加更新日志 zhaoshouqiang
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    //TODO 资产包修改记录
                    $changedAttributes = array();
                    foreach ($postdata as $key => $val) {
                        if ($oldinfo[$key] != $val) {
                            $changedAttributes[$key] = $val;
                        }
                    }
                    $package = new Package();
                    $re = $package->setUpdateLog($packageid, $changedAttributes, $userId, PackageUpdateLog::MODULE_BASE);
                    if (!$re['state']) {
                        throw new Exception($re['msg']);
                    }

                    $res = Yii::$app->db->createCommand()->update(Package::tableName(), $postdata, "id=$packageid")->execute();
                    if (!$res) {
                        throw new Exception('资产包基本信息更新失败');
                    }

                    //插入package_city表
                    //删除原先的表，添加现有的
//                    $packageCityList = PackageCity::find()->where(['package_id'=>$packageid])->all();
//                    if (!empty($packageCityList)) {
//                        foreach ($packageCityList as $packageCity) {
//                            $res = $packageCity->delete();
//                            if (!$res) {
//                                throw new Exception('资产包基本信息更新失败');
//                            }
//                        }
//                    }
//
//                    if (!empty($cityData)) {
//                        $model = new PackageCity();
//                        foreach($cityData as $value) {
//                            $_model = clone $model;
//                            $_model->package_id = $packageid;
//                            $_model->city_id = (int)$value;
//                            $_model->created_at = date('Y-m-d H:i:s');
//                            $res = $_model->save();
//                            if (!$res) {
//                                throw new Exception('资产包基本信息更新失败');
//                            }
//                        }
//                    }

                    $transaction->commit();
                    //---编辑资产包-发送消息--fly---
                    self::actionPostMessage($packageid);
                    //---编辑资产包-发送消息--fly---
                    $data = Responses::response200('', 0, '保存成功');//资产包基本信息更新
                } catch (Exception $e) {
                    $transaction->rollBack();
                    $data = Responses::response400('', 0, $e->getMessage());
                } catch (\Throwable $e) {
                    $transaction->rollBack();
                    $data = Responses::response400('', 0, $e->getMessage());
                }
            } else {
                $data = Responses::response404('资产包基本信息填写有误请重新填写');
            }
        }
        return json_encode($data);
    }

    /*
    *提交资产包转让信息---修改和添加
     * * @auth ly
     * 1持有人、2居间人
     * 1整包、2单户、3只参拍
     *  *holder持有人 lumper居间人
     * package_id
    */
    public function actionEidtTransfer()
    {
        $packageid = Yii::$app->session->get('packageid');
        $userId = Yii::$app->user->id;
        //$packageid=1;
        $list = array('contact', 'phone', 'address', 'email', 'position', 'remark');
        if (Yii::$app->request->isPost) {
            $postdata = Yii::$app->request->post();
            //整理获取的postdata
            $holderArray = array();//持有人
            $lumperArray = array();//居间人
            foreach ($list as $val) {
                $h = "h" . $val;
                $l = "l" . $val;
                switch ($val) {//数据验证
                    case $val == 'phone':
//                        if ((!preg_match("/^((0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?)|(1[34578]{1}\d{9})$/", $postdata[$h]) && !empty($postdata[$h])) || (!preg_match("/^((0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?)|(1[34578]{1}\d{9})$/", $postdata[$l]) && !empty($postdata[$l])))
//                            return json_encode(Responses::response404('转让信息-电话填写格式错误'));
                        break;
                    case $val == 'email':
                        if ((!filter_var($postdata[$h], FILTER_VALIDATE_EMAIL) && !empty($postdata[$h])) || (!filter_var($postdata[$l], FILTER_VALIDATE_EMAIL) && !empty($postdata[$l])))
                            return json_encode(Responses::response404('转让信息-邮箱填写格式错误'));
                        break;
                    default:
                }
                $holderArray[$val] = $postdata[$h];
                $lumperArray[$val] = $postdata[$l];
                unset($postdata['h' . $val]);
                unset($postdata['l' . $val]);
            }
            $holderArray = array_merge($holderArray, $postdata);
            $holderArray['package_id'] = $packageid;
            if ($postdata['transfer'] == 2) {//存在居间人
                $holderArray['transfer'] = 1;
                $lumperArray['transfer'] = 2;
                $lumperArray['package_id'] = $packageid;
            }
            $flag = 1;
            $res = PackageTransfer::find()->where("package_id=$packageid")->asArray()->all();

            //zhao shou qiang 添加修改日志
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $packageTransfer = new PackageTransfer();
                if ($res) {//编辑转让信息
                    // $flag = Yii::$app->db->createCommand()->update(Project::tableName(), $data[$id], "id=$id")->execute();
                    //查找持有人信息
                    $hId = PackageTransfer::find()->where("package_id=$packageid")->andWhere(['transfer' => 1])->asArray()->one();
                    $difFlag = 1;
                    $changedAttributes1 = array();
                    foreach ($holderArray as $key => $val) {
                        if ($hId[$key] != $val) {
                            $difFlag = 0;
                            $changedAttributes1[$key] = $val;
                        }
                    }
                    if (!$difFlag) {//持有人信息不同才能更新
                        // TODO 添加修改记录
                        $re = $packageTransfer->setUpdateLog($hId['id'], $packageid, $changedAttributes1, $userId, PackageUpdateLog::MODULE_TRANSFER, 2);
                        if (!$re['state']) {
                            throw new \Exception($re['msg']);
                        }

                        $flag = Yii::$app->db->createCommand()->update(PackageTransfer::tableName(), $holderArray, "id=:id", [':id' => $hId['id']])->execute();
                        if (!$flag)
                            throw new \Exception('转让信息-持有人信息修改失败');
                    }
                    if (isset($lumperArray['transfer']) && $lumperArray['transfer'] == 2) {//居间人存在
                        $lId = PackageTransfer::find()->where("package_id=$packageid")->andWhere(['transfer' => 2])->asArray()->one();
                        if ($lId) {//修改居间人
                            $difFlag = 1;
                            $changedAttributes2 = array();
                            foreach ($lumperArray as $key => $val) {
                                if ($lId[$key] != $val) {
                                    $difFlag = 0;
                                    $changedAttributes2[$key] = $val;
                                }
                            }
                            if (!$difFlag) {
                                // TODO 添加修改记录
                                $re = $packageTransfer->setUpdateLog($lId['id'], $packageid, $changedAttributes2, $userId, PackageUpdateLog::MODULE_TRANSFER, 2);
                                if (!$re['state']) {
                                    throw new \Exception($re['msg']);
                                }

                                $flag = Yii::$app->db->createCommand()->update(PackageTransfer::tableName(), $lumperArray, "id=:id", [':id' => $lId['id']])->execute();
                                if (!$flag)
                                    throw new \Exception('转让信息-居间人信息修改失败');
                            }
                        } else {//添加居间人
                            $flag = Yii::$app->db->createCommand()->insert(PackageTransfer::tableName(), $lumperArray)->execute();

                            // TODO 添加修改记录
                            $model = PackageTransfer::find()->where(['package_id' => $packageid, 'transfer' => $lumperArray['transfer']])->one();
                            $re = $packageTransfer->setUpdateLog($model['id'], $packageid, $model, $userId, PackageUpdateLog::MODULE_TRANSFER, 1);
                            if (!$re['state']) {
                                throw new \Exception($re['msg']);
                            }
                        }

                    } else {//是查找居间人删掉
                        $lId = PackageTransfer::find()->where("package_id=$packageid")->andWhere(['transfer' => 2])->one();
                        if ($lId) {
                            // TODO 添加修改记录
                            $re = $packageTransfer->setUpdateLog($lId['id'], $packageid, array(), $userId, PackageUpdateLog::MODULE_TRANSFER, 3);
                            if (!$re['state']) {
                                throw new \Exception($re['msg']);
                            }

                            if (!$lId->delete())
                                throw new \Exception('转让信息-居间人信息修改失败');
                        }
                    }
                    if ($flag) {
                        //---编辑资产包-发送消息--fly---
                        self::actionPostMessage($packageid);
                        //---编辑资产包-发送消息--fly---
                        $transaction->commit();
                        return json_encode(Responses::response200('', 0, '保存成功'));//转让信息-信息修改
                    } else {
                        throw new \Exception('保存失败');//转让信息-居间人信息修改
                    }

                } else {//添加转让信息
                    if (isset($lumperArray['transfer']) && $lumperArray['transfer'] == 2) {//存在居间人
                        $flag = Yii::$app->db->createCommand()->insert(PackageTransfer::tableName(), $lumperArray)->execute();

                        // TODO 添加修改记录
                        $model = PackageTransfer::find()->where(['package_id' => $packageid, 'transfer' => $lumperArray['transfer']])->one();
                        $re = $packageTransfer->setUpdateLog($model['id'], $packageid, $model, $userId, PackageUpdateLog::MODULE_TRANSFER, 1);
                        if (!$re['state']) {
                            throw new \Exception($re['msg']);
                        }
                    }
                    if (!$flag) {
                        throw new \Exception('转让信息-居间人信息添加失败');
                    }

                    $flag = Yii::$app->db->createCommand()->insert(PackageTransfer::tableName(), $holderArray)->execute();
                    if ($flag) {
                        // TODO 添加修改记录
                        $model = PackageTransfer::find()->where(['package_id' => $packageid, 'transfer' => $holderArray['transfer']])->one();
                        $re = $packageTransfer->setUpdateLog($model['id'], $packageid, $model, $userId, PackageUpdateLog::MODULE_TRANSFER, 1);
                        if (!$re['state']) {
                            throw new \Exception($re['msg']);
                        }
                        //---编辑资产包-发送消息--fly---
                        self::actionPostMessage($packageid);
                        //---编辑资产包-发送消息--fly---
                        $transaction->commit();
                        $transaction->commit();
                        return json_encode(Responses::response200('', 0, '保存成功'));//转让信息更新
                    } else {
                        throw new \Exception('保存失败');//转让信息-持有人信息添加
                    }
                }
            } catch (\Exception $e) {
                $transaction->rollBack();
                return json_encode(Responses::response404($e->getMessage()));
            } catch (\Throwable $e) {
                $transaction->rollBack();
                return json_encode(Responses::response404($e->getMessage()));
            }


            /*if ($res) {//编辑转让信息
                // $flag = Yii::$app->db->createCommand()->update(Project::tableName(), $data[$id], "id=$id")->execute();
                //查找持有人信息
                $hId = PackageTransfer::find()->where("package_id=$packageid")->andWhere(['transfer' => 1])->asArray()->one();
                $difFlag = 1;
                foreach ($holderArray as $key => $val) {
                    if ($hId[$key] != $val) {
                        $difFlag = 0;
                        break;
                    }
                }
                if (!$difFlag) {//持有人信息不同才能更新
                    $flag = Yii::$app->db->createCommand()->update(PackageTransfer::tableName(), $holderArray, "id=:id", [':id' => $hId['id']])->execute();
                    if (!$flag) return json_encode(Responses::response404('转让信息-持有人信息修改失败'));
                }
                if (isset($lumperArray['transfer']) && $lumperArray['transfer'] == 2) {//居间人存在
                    $lId = PackageTransfer::find()->where("package_id=$packageid")->andWhere(['transfer' => 2])->asArray()->one();
                    if ($lId) {//修改居间人
                        $difFlag = 1;
                        foreach ($lumperArray as $key => $val) {
                            if ($lId[$key] != $val) {
                                $difFlag = 0;
                                break;
                            }
                        }
                        if (!$difFlag) {
                            $flag = Yii::$app->db->createCommand()->update(PackageTransfer::tableName(), $lumperArray, "id=:id", [':id' => $lId['id']])->execute();
                            if (!$flag) return json_encode(Responses::response404('转让信息-居间人信息修改失败'));
                        }
                    } else {//添加居间人
                        $flag = Yii::$app->db->createCommand()->insert(PackageTransfer::tableName(), $lumperArray)->execute();
                    }
                } else {//是查找居间人删掉
                    $lId = PackageTransfer::find()->where("package_id=$packageid")->andWhere(['transfer' => 2])->one();
                    if ($lId) {
                        if (!$lId->delete()) return json_encode(Responses::response404('转让信息-居间人信息修改失败'));
                    }
                }
                if ($flag) {
                    //---编辑资产包-发送消息--fly---
                    self::actionPostMessage($packageid);
                    //---编辑资产包-发送消息--fly---
                    return json_encode(Responses::response200('', 0, '转让信息-信息修改成功'));
                } else {
                    return json_encode(Responses::response404('转让信息-居间人信息修改失败'));
                }
            } else {//添加转让信息
                if (isset($lumperArray['transfer']) && $lumperArray['transfer'] == 2) {//存在居间人
                    $flag = Yii::$app->db->createCommand()->insert(PackageTransfer::tableName(), $lumperArray)->execute();
                }
                if (!$flag) {
                    return json_encode(Responses::response404('转让信息-居间人信息添加失败'));
                }
                $flag = Yii::$app->db->createCommand()->insert(PackageTransfer::tableName(), $holderArray)->execute();
                if ($flag) {
                    return json_encode(Responses::response200('', 0, '转让信息更新成功'));
                } else {
                    return json_encode(Responses::response404('转让信息-持有人信息添加失败'));
                }

            }*/

        }

    }

    /*
    *编辑（添加和修改）-流转历史记录 提交
     * * * @auth ly
     * package_transfer_history_init/package_transfer_history
     * 两个表都类似于初始化(NO USE)
     *
    */
    public function actionAddTransferHistory()
    {//添加两个表
        if (Yii::$app->request->isPost) {
            $userId = Yii::$app->user->id;
            $packageid = Yii::$app->session->get('packageid');
            //$packageid=1;
            $postdata = Yii::$app->request->post();
            $data = array();//格式化后提交数据
            foreach ($postdata as $key => $val) {
                preg_match("/([a-z_]*)(\d*)$/", $key, $value);//提取信息存数组
                if ($val != '') {
                    $data[$value[2]][$value[1]] = $val;
                }

            }
            if ($packageid > 0) {
                PackageTransferHistory::deleteAll("package_id=$packageid");
                PackageTransferHistoryInit::deleteAll("package_id=$packageid");
                // PackageTransferHistoryInit
            }
            $historymodel = new PackageTransferHistory();
            $historyinitmodel = new PackageTransferHistoryInit();

            $ordersum = count($data);
            $data = array_reverse($data);
            if (empty($data)) return json_encode(Responses::response400('请填写流转历史记录后提交'));
            foreach ($data as $attributes) {
                $attributes['package_id'] = $packageid;
                $attributes['created_at'] = date('Y-m-d H:i:s');
                $attributes['order'] = $ordersum;
                $_historymodel = clone  $historymodel;
                $_historymodel->setAttributes($attributes);
                $historyflag = $_historymodel->save();
                //TODO 记录
                if ($historyflag) {
                    $historymodel->setUpdateLog($_historymodel->id, $_historymodel->package_id, $_historymodel, $userId, PackageUpdateLog::MODULE_CONVERSION, 1);
                }
                $_historyinitmodel = clone $historyinitmodel;
                $_historyinitmodel->setAttributes($attributes);
                $historyinitflag = $_historyinitmodel->save();
                if (!$historyflag || !$historyinitflag) {
                    //  var_dump($_historyinitmodel->getErrors());
                    return json_encode(Responses::response404('保存失败'));//流转历史记录-添加
                }
                $ordersum--;
            }
            //---编辑资产包-发送消息--fly---
            self::actionPostMessage($packageid);
            //---编辑资产包-发送消息--fly---
            return json_encode(Responses::response200('', 0, '保存成功'));//流转历史记录更新
        }
        return json_encode(Responses::response404('流转历史记录访问有误'));
    }

    /*资产包修改流转记录（只修改package_transfer_history表）
    * * @auth ly
    */
    public function actionUpdateTransferHistory()
    {
        if (Yii::$app->request->isPost) {
            $userId = Yii::$app->user->id;
            $packageid = Yii::$app->session->get('packageid');
            $postdata = Yii::$app->request->post();
            $data = array();//格式化后提交数据
            foreach ($postdata as $key => $val) {
                preg_match("/([a-z_]*)(\d*)$/", $key, $value);//提取信息存数组
                if ($val != '') {
                    $data[$value[2]][$value[1]] = $val;
                }
            }
            $data = array_reverse($data);
            $historymodel = new PackageTransferHistory();
            $ordersum = count($data);//计数order
            if (empty($data)) return json_encode(Responses::response400('请填写流转历史记录后提交'));


            //TODO 操作记录
            $transaction = Yii::$app->db->beginTransaction();
            try {
                foreach ($data as $attributes) {
                    $attributes['package_id'] = $packageid;
                    $attributes['created_at'] = date('Y-m-d H:i:s');
                    $attributes['order'] = $ordersum;
                    $_historymodel = clone  $historymodel;
                    $state = false;// true 是修改，false是新增
                    $changedAttributes = array();//修改的值
                    if (isset($attributes['id'])) {//更新数据
                        $state = true;
                        $_historymodel = $_historymodel::findOne($attributes['id']);
                        if ($_historymodel === null) {
                            throw new NotFoundHttpException;
                        } else {
                            if ($_historymodel->transfer_date != $attributes['transfer_date']) {
                                $changedAttributes['transfer_date'] = $attributes['transfer_date'];
                            }

                            if ($_historymodel->transfer != $attributes['transfer']) {
                                $changedAttributes['transfer'] = $attributes['transfer'];
                            }

                            if ($_historymodel->content != $attributes['content']) {
                                $changedAttributes['content'] = $attributes['content'];
                            }

                            if ($_historymodel->remark != $attributes['remark']) {
                                $changedAttributes['remark'] = $attributes['remark'];
                            }

                            if ($_historymodel->order != $attributes['order']) {
                                $changedAttributes['order'] = $attributes['order'];
                            }
                        }
                        unset($attributes['id']);
                    }
                    $_historymodel->setAttributes($attributes);

                    //修改
                    if ($state) {
                        if (!empty($changedAttributes)) {
                            //TODO 记录
                            $re = $historymodel->setUpdateLog($_historymodel->id, $packageid, $changedAttributes, $userId, PackageUpdateLog::MODULE_CONVERSION, 2);
                            if (!$re['state'])
                                throw new \Exception($re['msg']);
                        }
                    }
                    $historyflag = $_historymodel->save();
                    if (!$historyflag) {
                        throw new \Exception('流转历史记录-更新失败');
                    } else {
                        //新增
                        if (!$state) {
                            //TODO 记录
                            $re = $historymodel->setUpdateLog($_historymodel->id, $packageid, $_historymodel, $userId, PackageUpdateLog::MODULE_CONVERSION, 1);
                            if (!$re['state'])
                                throw new \Exception($re['msg']);
                        }
                    }
                    $ordersum--;
                }
                //---编辑资产包-发送消息--fly---
                self::actionPostMessage($packageid);
                //---编辑资产包-发送消息--fly---
                $transaction->commit();
                return json_encode(Responses::response200('', 0, '保存成功'));//流转历史记录更新
            } catch (\Exception $e) {
                $transaction->rollBack();
                return json_encode(Responses::response404($e->getMessage()));
            } catch (\Throwable $e) {
                $transaction->rollBack();
                return json_encode(Responses::response404($e->getMessage()));
            }


//            foreach ($data as $attributes) {
//                $attributes['package_id'] = $packageid;
//                $attributes['created_at'] = date('Y-m-d H:i:s');
//                $attributes['order'] = $ordersum;
//                $_historymodel = clone  $historymodel;
//                if (isset($attributes['id'])) {//更新数据
//                    $_historymodel = $_historymodel::findOne($attributes['id']);
//                    if ($_historymodel === null) {
//                        throw new NotFoundHttpException;
//                    }
//                    unset($attributes['id']);
//                }
//                $_historymodel->setAttributes($attributes);
//                $historyflag = $_historymodel->save();
//                if (!$historyflag) {
//                    //  var_dump($_historyinitmodel->getErrors());
//                    return json_encode(Responses::response404('流转历史记录-更新失败'));
//                }
//                $ordersum--;
//            }
//
//            return json_encode(Responses::response200('', 0, '流转历史记录更新成功'));

        }
        return json_encode(Responses::response404('更新流转历史记录访问有误'));
    }

    /*
     * 删除-流转前期处置及维护情况(完善信息中信息都是新插入的所以删除的时候不用后台)
     * package_transfer_history（编辑才页面需要）
     * * @auth ly
     * */
    public function actionDelTransferHistory()
    {
        /*获取转让id 通过id 删除
        *如新添加还未入库数据提价删除直接默认返true、// Package::deleteAll("package_id=111")
        */
        if (Yii::$app->request->isPost) {
            $id = Yii::$app->request->post('id');
            $userId = Yii::$app->user->id;
            if ($id >= 0) {
                $delID = PackageTransferHistory::find()->where("id=$id")->one();

                $transaction = Yii::$app->db->beginTransaction();
                try {
                    //TODO 记录
                    $re = (new PackageTransferHistory())->setUpdateLog($id, $delID->package_id, array(), $userId, PackageUpdateLog::MODULE_CONVERSION, 3);
                    if (!$re['state']) {
                        throw new \Exception($re['message']);
                    }
                    if ($delID->delete()) {
                        //---编辑资产包-发送消息--fly---
                        self::actionPostMessage($delID->package_id);
                        //---编辑资产包-发送消息--fly---
                        $transaction->commit();
                        return json_encode(Responses::response200($id, 0, '成功删除-日期为:' . $delID['transfer_date'] . '的流转、前期处置及维护情况'));
                    }
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    return json_encode(Responses::response404($e->getMessage()));
                } catch (\Throwable $e) {
                    $transaction->rollBack();
                    return json_encode(Responses::response404($e->getMessage()));
                }

//                if ($delID->delete() && $re['state']) {
//                    return json_encode(Responses::response200($id, 0, '成功删除-日期为:' . $delID['transfer_date'] . '的流转、前期处置及维护情况'));
//                }
            }
        }
        return json_encode(Responses::response404('删除流转历史记录访问有误'));
    }

    /*
    *提交（添加）--项目列表
     * * * @auth ly
     * Yii::$app->db->createCommand()->update('table', ['name' => $name], "id = {$id}")->execute();
     *update 第一个参数:表名 第二个参数 :要修改为的数据 第三个数据:修改条件
    */
    public function actionEditProjectList()
    {
        $list = ['borrower', 'principal', 'interest', 'is_suit', 'guarantor', 'warranty'];
        $data = array();
        if (Yii::$app->request->isPost) {
            $packageId = Yii::$app->session->get('packageid');
            $postdata = Yii::$app->request->post();
            foreach ($postdata as $key => $val) {
                preg_match("/(\d*)$/", $key, $id);//提取项目id
                $id = $id[0];
                if (!isset($data[$id])) {
                    foreach ($list as $k) {
                        $data[$id][$k] = $postdata[$k . $id];
                        switch ($k) {//数据验证
                            case $k == 'borrower':
                                if (empty($postdata[$k . $id]))
                                    return json_encode(Responses::response404('项目列表-借款人名称不能为空'));
                                break;
                            case $k == 'principal':
                                if (!is_numeric($postdata[$k . $id]))
                                    return json_encode(Responses::response404('项目列表-本金格式错误'));
                                break;
                            case $k == 'interest':
                                if (!is_numeric($postdata[$k . $id]))
                                    return json_encode(Responses::response404('项目列表-利息格式错误'));
                            default:
                        }
                    }
                    //编辑入库
                    $oldProject = Project::find()->select($list)->where("id=$id")->asArray()->one();
                    if ($oldProject != $data[$id]) {//数据库与提交数据比较，不同更新
                        $flag = Yii::$app->db->createCommand()->update(Project::tableName(), $data[$id], "id=$id")->execute();
                        if (!$flag) {
                            return json_encode(Responses::response400('数据插入失败'));//数据插入失败400
                        }
                    }
                }
            }
            Yii::$app->session->remove('packageid');//删除上传资产包id
            //完成资产包
            if ($packageId > 0) {
                $transaction = Yii::$app->db->beginTransaction();
                try {
//                    $package = Package::findOne($packageId);
//                    $package->is_finished = 1;
//                    $re = $package->save();
                    $re = Yii::$app->db->createCommand()->update(Package::tableName(), ['is_finished' => 1], "id=$packageId")->execute();
                    if (!$re) {
                        throw new Exception('保存1失败');
                    }
                    //更新资产包下的项目的是否完成状态
                    //TODO 项目清单可为空
                    $projectList = Project::find()->where(['package_id' => $packageId])->all();
                    if (!empty($projectList)) {
                        $flag = Yii::$app->db->createCommand()->update(Project::tableName(), ['is_finished' => 1], "package_id=$packageId")->execute();
                        if (!$flag) {
                            throw new Exception('保存2失败');
                        }
                    }

                    $transaction->commit();
                    return json_encode(Responses::response200('', 0, '项目列表成功入库'));//数据插入成功200
                } catch (Exception $e) {
                    $transaction->rollBack();
                    return json_encode(Responses::response400($e->getMessage()));//数据插入失败400
                }
//                $package = Package::findOne($packageId);
//                $package->is_finished = 1;
//                $re = $package->save();
//                if (!$re) {
//                    $error = $package->getFirstErrors();
//                    $msg = '';
//                    foreach ($error as $value) {
//                        $msg .= $value;
//                    }
//                    return json_encode(Responses::response400($msg));//数据插入失败400
//                }
            }
        }
        return json_encode(Responses::response404('访问有误'));//提交方式出错或未找到页面404

    }

    /*删除--项目列表一条信息
    * * @auth ly
    */
    public function actionDelProjectList()
    {
        if (Yii::$app->request->isPost) {
            $id = Yii::$app->request->post('id');
            $package_id = (new \yii\db\Query())->from('project')->where(['=', 'id', $id[0]])->one()['package_id'];
            if (is_array($id)) {//批量删除项目
                foreach ($id as $val) {
                    $project = Project::find()->where("id=$val")->one();
                    //目前只删除项目是否要删除项目关联的所有表？？？
                    if (!$project->delete()) {
                        return json_encode(Responses::response400('项目未能删除请重新操作'));
                    }
                }
                //---编辑资产包-发送消息--fly---
                self::actionPostMessage($package_id);
                //---编辑资产包-发送消息--fly---
                return json_encode(Responses::response200($id, 0, '成功删除单项目'));
            } else {//删除单个项目

                $project = Project::find()->where("id=$id")->one();
                if ($project->delete()) {
                    //---编辑资产包-发送消息--fly---
                    self::actionPostMessage($package_id);
                    //---编辑资产包-发送消息--fly---
                    return json_encode(Responses::response200($id, 0, '成功删除单项目'));
                }
            }
        }
        return json_encode(Responses::response400('操作有误'));
    }

    /**资产包详情------新增项目
     * @ly
     */
    public function actionAddProject()
    {
        if (Yii::$app->request->isPost) {
            $postData = Yii::$app->request->post();
            if (isset($postData['borrower'])) {
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    $postData['title'] = $postData['borrower'];
                    $postData['created_at'] = date('Y-m-d H:i:s');
                    $postData['is_suit'] = 0;
                    $postData['interest'] = empty($postData['interest']) ? '0' : $postData['interest'];
                    $postData['is_finished'] = 1; //0为未完成上传,完成上传
                    $typeid = $postData['type'];
                    $package_id = $postData['package_id'];
                    $model = new Project();
                    if ($model->load($postData, '') && $model->save()) {
                        $project_id = $model->attributes['id'];//leader manager
                        $package_leader = PackageInitiation::find()->select('leader')->where(['package_id' => $package_id])->one();
                        if ($package_leader) {
                            $projectTeamModel = new ProjectTeam();
                            $teamData = array('project_id' => $project_id, 'manager' => $package_leader['leader']);
                            if (!$projectTeamModel->load($teamData, '') || !$projectTeamModel->save()) {
                                throw new Exception('保存失败');
                            }
                        }
                        //return json_encode(Responses::response200('', $typeid, '保存成功'));//新增单项目
                    } else {
                        $errors = $model->getErrors();
                        foreach ($errors as $key => $val) {
                            $errorOne = $val[0];
                            break;
                        }
                        throw new Exception($errorOne);//throw new \Exception('这里是错误原因');
                        // return json_encode(Responses::response404($errorOne));
                    }
                    //---编辑资产包-发送消息--fly---
                    self::actionPostMessage($postData['package_id']);
                    //---编辑资产包-发送消息--fly---
                    $transaction->commit();
                    return json_encode(Responses::response200('', $typeid, '保存成功'));//新增单项目
                } catch (Exception $e) {
                    $error = $e->getMessage();  //获取抛出的错误
                    return json_encode(Responses::response404($error));
                    $transaction->rollBack();
                }
            } else {
                $packageid = Yii::$app->request->post('packageid');
                $type = Yii::$app->request->post('type');
                if (is_numeric($packageid) && is_numeric($type)) {
                    $provinceList = Country::find()->where("pid=0")->asArray()->all();
                    return $this->renderPartial('modal/asset-package-editing-adds', ['packageid' => $packageid, 'type' => $type, 'provinceList' => $provinceList]);
                }
            }
        }
        return json_encode(Responses::response400('操作有误'));
    }

    /*资产包详情----移动到抵押列表或是移动到混合类列表
    *@ly
    */
    public function actionMove()
    {
        if (Yii::$app->request->isAjax) {
            $projectId = Yii::$app->request->post('ids');
            $type = Yii::$app->request->post('type');
            if (is_array($projectId) && count($projectId) > 0 && ($type == 1 || $type == 2)) {
                foreach ($projectId as $val) {
                    $project = Yii::$app->db->createCommand()->update(Project::tableName(), ['type' => $type], "id=:id", [':id' => $val])->execute();
//                    $project=Project::find()->where(['id'=>$val])->one();
//                    $project->type = $type; !$project->update(['type'])
                    if (!$project) {
                        // var_dump($project);
                        return json_encode(Responses::response404('单项目移动失败'));
                    }
                }
                //---编辑资产包-发送消息--fly---
                if (!empty($projectId[0])) {
                    $package_id = (new \yii\db\Query())->from('project')->where(['=', 'id', $projectId[0]])->one()['package_id'];
                    self::actionPostMessage($package_id);
                }
                //---编辑资产包-发送消息--fly---
                return json_encode(Responses::response200('', '1', '单项目移动成功'));
            }
            return json_encode(Responses::response400('数据有误'));
        }
        return json_encode(Responses::response400('操作有误'));
    }

    /**资产包详情------计算求和
     * @ly
     */
    public function actionCalculate()
    {
        if (Yii::$app->request->isAjax) {
            $projectId = Yii::$app->request->post('ids');
            $type = Yii::$app->request->post('type');
            $principal = 0;//本金
            $interest = 0;//利息
            $reservation = 0;//保守
            $radical = 0;//激进
            if (is_array($projectId) && count($projectId) > 0) {
                foreach ($projectId as $id) {
                    if ($type == 2) {//抵押类计算'payment_reservation' => ('回现保守'),'payment_radical' => ('回现激进'),
                        $res = Project::find()->with('payment')->where(['id' => $id])->asArray()->all();//project_id
                        if ($res) {
                            $val = $res[0];
                            $principal += (float)$val['principal'];
                            $interest += (float)$val['interest'];
                            if ($val['payment']) {
                                $reservation += (float)($val['payment']['payment_reservation']);
                                $radical += (float)($val['payment']['payment_radical']);
                            }
                        }
                    } else {//保证混合类计算'conservation' => ('保守回收预估值') 'radical' => ('激进回收预估值')
                        $res = Project::find()->with('evaluation')->where(['id' => $id])->asArray()->all();//project_id
                        if ($res) {
                            $val = $res[0];
                            $principal += (float)$val['principal'];
                            $interest += (float)$val['interest'];
                            if ($val['evaluation']) {
                                $reservation += (float)($val['evaluation']['conservation']);
                                $radical += (float)($val['evaluation']['radical']);
                            }
                        }
                    }
                }
            }
            return $this->renderPartial('modal/asset-package-editing-calculate', ['principal' => $principal, 'interest' => $interest, 'reservation' => $reservation, 'radical' => $radical]);
        }
        return json_encode(Responses::response400('操作有误'));
    }

    /**资产包详情------高级筛查
     * @ly
     */
    public function actionFiltrate()
    {
        if (Yii::$app->request->isAjax) {
            $typeid = Yii::$app->request->post('typeid');
            $keyWords = Yii::$app->request->post('keyWords');
            $provinceList = Country::find()->where("pid=0")->asArray()->all();
            return $this->renderPartial('modal/asset-package-editing-filtrate', ['keyWords' => $keyWords, 'typeid' => $typeid, 'provinceList' => $provinceList]);

        }
        return json_encode(Responses::response400('操作有误'));
    }

    /*资产包详情---项目 下载   (ly)*/
    public function actionDownProjects()
    {
        if (Yii::$app->request->isGet) {
            // $type=2; $postIds=[1,4,6,7,8];
            $dataListDY = array();
            $dataListHH = array();
            $type = Yii::$app->request->get('type');
            $logStr = '';
            if ($type <> 2) {//下载混合类列表 1和3
                $dataListHH = $projectListHH = Project::find()->with('provinceName', 'cityName', 'lawsuit', 'evaluation', 'note')->where(['<>', 'type', 2]);//->where(['in','id',$postIdsHH])->asArray()->all()
                $logStr .= '混合类';
            }
            if ($type <> 1) {//2和3
                $dataListDY = (new \yii\db\Query())
                    ->from('project AS p')
                    ->select('
                p.package_id,p.id,p.borrower,p.principal,p.interest,p.is_suit,p.management_status,p.enterprise,p.industry,p.guarantor,p.guarantor_status,p.mortgage_details,p.is_highlights,pc.title as pctitle,pcc.title as pcctitle,
                l.judgement,l.execution,l.court,l.block,
                m.mortgage_principal,m.mortgage_interest,s.mortgage_type,s.mortgage_owner,s.mortgage_code,s.mortgage_district,s.mortgage_address,s.mortgage_building_area,s.mortgage_land_area,,s.maximum_mortgage,s.remaining_service_life,
                s.mortgage_order,s.is_first_mortgage,s.mortgage_future,s.mortgage_situation,
                s.mortgage_seal_order,s.is_first_seal,s.mortgage_seal_state,
                i.building_title,i.finished_date,i.total_floor,i.which_floor,i.surroundings,i.property,i.property_state,i.whether_work,i.lease_info,i.is_only,i.willing,i.market_price,i.market_rent_price,i.comparison_property1,i.comparison_property2,i.comparison_property3,i.comparison_property4,i.info_origin,i.contact,i.remark,
                v.bank_value,v.third_partner_value,v.third_partner_value_other,v.auction_price,v.market_conserve_price,v.market_radical_price,v.market_conservation_total_price,v.market_radical_total_price,v.payment_reservation as vpayment_reservation,v.payment_radical as vpayment_radical,v.price_reason,
                ov.bought_analysis,ov.bought_reservation,ov.bought_radical,ov.mortgage_other_seal_order,ov.mortgage_other_seal_state,
                c.payment_reservation,c.payment_radical,c.payment_tax,c.payment_month,c.payment_analysis')
                    ->leftJoin('project_pre_evaluation_mortgage AS m', 'm.project_id = p.id')
                    ->leftJoin('project_pre_evaluation_seal as s', 's.mortgage_id=m.id')
                    ->leftJoin('project_pre_evaluation_lawsuit AS l', 'l.project_id = p.id')
                    ->leftJoin('project_pre_evaluation_interview AS i', 'i.mortgage_id=m.id')
//                    ->leftJoin('project_pre_evaluation_value AS v', 'v.mortgage_id = m.id')
                    ->leftJoin('project_pre_evaluation_value AS v', 'v.ppes = s.id')
                    ->leftJoin('project_pre_evaluation_other_value AS ov', 'ov.project_id = p.id')
//                    ->leftJoin('project_pre_evaluation_other_value AS ov', 'ov.mortgage_id = m.id')
                    ->leftJoin('project_payment_collection AS c', 'c.project_id = p.id')
                    ->leftJoin('country AS pc', 'pc.id = p.province')
                    ->leftJoin('country AS pcc', 'pcc.id = p.city')->where(['type' => 2]);
                //->where(['in','p.id',$postIdsDY])->all();
                $logStr .= ' 抵押类';
            }
            if (Yii::$app->request->get('packageid') > 0) {//资产包下载报告中下载xls
                $packageid = Yii::$app->request->get('packageid');
                if ($type <> 2) {//下载混合类列表 1和3
                    $dataListHH = $dataListHH->andWhere(['package_id' => $packageid])->asArray()->all();
                }
                if ($type <> 1) {//2和3
                    $dataListDY = $dataListDY->andWhere("p.package_id=$packageid")->all();
                }
            } else {//资产包详情中 项目列表中选中的下载
                $postIdsHH = explode(',', Yii::$app->request->get('ids'));
                $postIdsDY = $postIdsHH;
                if ($type <> 2) {//下载混合类列表 1和3
                    $dataListHH = $dataListHH->where(['in', 'id', $postIdsHH])->asArray()->all();
                }
                if ($type <> 1) {//2和3
                    $dataListDY = $dataListDY->where(['in', 'p.id', $postIdsDY])->all();
                }
            }
            $packageid = Yii::$app->session->get('packageid');
            //添加资产包操作日志-开始
            $packageLog = new PackageLog();
            $packageLog->package_id = $packageid;
            $packageLog->created_at = date('Y-m-d H:i:s', time());
            $packageLog->user_id = Yii::$app->user->id;
            $packageLog->log = '下载' . $logStr . '项目清单';
            $packageLog->save();
            //添加资产包操作日志-结束
            $packageInfo = Package::findOne($packageid);
            $excel = new Excel();
            $excel->createExcelProjects($type, $dataListHH, $dataListDY, $packageInfo->title . '项目清单.xlsx');//【资产包名称】+项目清单
        }
    }

    /*资产包下载报告 显示弹出框及提交下载立项报告*/
    public function actionShowDownPage()
    {
        if (Yii::$app->request->get('packageid') > 0 && Yii::$app->request->get('setUpFile')) {
            $packageid = Yii::$app->request->get('packageid');
            $projectsType2Principal = Project::find()->where(['package_id' => $packageid])->andWhere(['type2' => 2])->sum('principal');//抵押本金
            $projectsSuit = Project::find()->where(['package_id' => $packageid])->andWhere(['is_suit' => 1]);
            $projectsSuitCount = $projectsSuit->count();//已诉项目户数
            $projectsSuitPrincipal = $projectsSuit->sum('principal'); // 已诉本金
            $data = Package::find()->with('initiation', 'history', 'income', 'plan')->where(['id' => $packageid])->asArray()->all();
            $principalB = $data[0]['principal'] > 0 ? round(($projectsSuitPrincipal / $data[0]['principal'] * 100), 2) . '%' : 0;
            //添加资产包操作日志-开始
            $packageLog = new PackageLog();
            $packageLog->package_id = $packageid;
            $packageLog->created_at = date('Y-m-d H:i:s', time());
            $packageLog->user_id = Yii::$app->user->id;
            $packageLog->log = '下载立项报告';
            $packageLog->save();
//            if (!$packageLog->save()) {
//                throw new Exception('资产包操作日志保存失败');
//            }
            //添加资产包操作日志-结束
            return $this->renderPartial('down-templet/down-load-setup',
                [
                    'data' => $data[0],
                    'projectsType2Principal' => $projectsType2Principal,
                    'projectsSuitCount' => $projectsSuitCount,
                    'principalB' => $principalB
                ]);
        }
        return $this->render('modal/asset-package-editing-download', ['packageId' => Yii::$app->session['packageid']]);
    }

    /*资产包基本信息上锁 开始编辑
    *传值package_id
     * * * @auth ly
     */
    public function getLock($_tableName, $_key, $_id)
    {
        //$res=$_model::find()->with('user')->where("$_key=$_id")->asArray()->one();
        $res = (new Query())->from($_tableName . ' as TB')
            ->select('TB.lock_user,TB.lock_timestamp,U.realname')
            ->leftJoin(User::tableName() . ' as U', 'U.id=TB.lock_user')
            ->where("TB.$_key=$_id")->one();

        if (empty($res['lock_user']) && empty($res['lock_timestamp'])) {
            $changeData = [
                'lock_user' => Yii::$app->user->id,
                'lock_timestamp' => date('Y-m-d H:i:s')
            ];
            $res = Yii::$app->db->createCommand()->update($_tableName, $changeData, "$_key=$_id")->execute();
            if ($res) {
                return array(TRUE, '');
            } else {
                return array(FALSE, '系统有误，请稍后重试');
            }
        } else {
            if ($res['lock_user'] == Yii::$app->user->id) {
                return array(TRUE, '');
            } else {
                return array(FALSE, $res['realname'] . '正在编辑');
            }
        }
        //$res = Yii::$app->db->createCommand()->update($_tableName, , "$_key=$_id")->execute();

    }

    /*资产包基本信息取消锁 结束编辑
    *传值package_id
     * * * @auth ly
     */
    public function getUnLock($_tableName, $_key, $_id)
    {
        //$res=$_model::find()->with('user')->where("$_key=$_id")->asArray()->one();
        $res = (new Query())->from($_tableName)->where("$_key=$_id")->one();
        $userID = Yii::$app->user->id;
        if ($res['lock_user'] == $userID) {
            $changeData = [
                'lock_user' => '',
                'lock_timestamp' => ''
            ];
            $res = Yii::$app->db->createCommand()->update($_tableName, $changeData, "$_key=$_id")->execute();
            if (!$res) {
                return array(FALSE, '系统有误，请稍后重试');
            }
        }
        return array(TRUE, '');
    }

    /*资产包详情 项目列表弹出编辑框
    *get 传值
    *返回 html 代码 展示编辑页
     * * * * @auth ly
    */
    public function actionShowFieldPage()
    {
        if (Yii::$app->request->isPost) {
            $eidtFlage = false;
            if (DtActionFilter::checkPackage('package_edit', Yii::$app->session->get('packageid'))) {
                $eidtFlage = true;
            }
            $postData = Yii::$app->request->post();
            if (empty($postData['fdShowName'])) {
                $fd = $postData['fd'];
                $postData['fdShowName'] = Yii::$app->params[$fd];
            }
            return $this->renderPartial('modal/asset-package-editing-input', ['data' => $postData, 'eidtFlage' => $eidtFlage]);
        }
        throw new \Exception('访问有误');
    }

    /*资产包详情 项目列表字段编辑 提交接口
    //tb:tbName 表名称缩写,fd:fdName需更改的字段名称,keyId:keyId 表主键值,content:fdContent修改后的内容
    */
    public function actionEditField()
    {

        if (Yii::$app->request->isPost) {
            $postData = Yii::$app->request->post();
            if (!empty($postData['tb']) && !empty($postData['fd'])) {
                $tbList = Yii::$app->params['tbList'];
                $tbName = $tbList[$postData['tb']]['tbName'];//表名称
                $keyFdName = $tbList[$postData['tb']]['keyFdName'];//表主键名称
                $keyId = $postData['keyId'];
                $content = $postData['content'];
                $fdContent = $postData['fd'];
                $res = (new Query())->from($tbName)->where("$keyFdName=$keyId")->one();
                if ($res) {
                    $flag = Yii::$app->db->createCommand()->update($tbName, [$fdContent => $content], "$keyFdName=$keyId")->execute();
                    if ($flag) {
                        return json_encode(Responses::response200('', 0, '更新成功'));
                    }
                }
                return json_encode(Responses::response400('该数据不存在，不能修改'));
            }

        }
        return json_encode(Responses::response400('操作有误'));
    }

    public static function actionPackageToCalculate($package_id)
    {
        return self::getAllCalculate($package_id);
    }


    public static function actionPostMessage($package_id)
    {
        //----编辑资产包发送消息---------------------
//        $package_id         = !empty($teamMembersData['package_id'])?intval($teamMembersData['package_id']):0;
        //根据package_id获取标题
        $pack_name = (new \yii\db\Query())->from(Package::tableName())->where(['=', 'id', $package_id])->one();
        //根据package_id获取状态
        $appStates = (new \yii\db\Query())->select('state')->from(Package::tableName())->where(['=', 'id', $package_id])->one();
        $appStateName = \Yii::$app->params['packageStatus'][$appStates['state']];//当前状态
        //最后一次更新人员
        $sender_id = \Yii::$app->user->getId();
        $userName = (new \Yii\db\Query())->from(User::tableName())->leftJoin('auth_item as ai', 'ai.name = user.department')->where(['=', 'id', $sender_id])->one();
        $message = [
            'pack_name' => $pack_name,
            'appStates' => $appStateName,
            'lastUpdateUser' => $userName['realname'],
            'lastUpdateUserBumen' => $userName['description'],
        ];
        //发送给关注此资产包的用户
        $user_id = (new \yii\db\Query())->from('package_like')->select('user_id')->where(['=', 'type', 1])->andWhere(['=', 'package_id', $package_id])->all();
        $user_id = array_column($user_id, 'user_id');
        if (!empty($user_id) && is_array($user_id)) {
            //如果关注的用户中有自己（编辑用户），则从发送的消息人中删除 2018年3月5日14:52:06 von
            if (in_array($sender_id, $user_id)) {
                foreach ($user_id as $ku => $vu) {
                    if ($vu == $sender_id) {
                        unset($user_id[$ku]);
                    }
                }
            }
        }
        if (!empty($user_id) && is_array($user_id)) {
            $data = [];
            $data['sender'] = \Yii::$app->user->getId();//发件人id
            $data['package_project_id'] = $package_id;//资产包id
            $data['is_package'] = 1;//是否是资产包/1是资产包/2是项目
            $data['message_val'] = json_encode($message); //消息内容 json

            $data['user_id'] = $user_id;//收件人id
            $data['message_state'] = \Yii::$app->params['UNREND'];//消息状态 0未阅读 1已阅读
            $data['message_group'] = \Yii::$app->params['GUANZHU_UP']; //消息分类 1待审批提醒 2审批反馈 3关注更新*/

            $param = [];
            $param['where_sender'] = \Yii::$app->user->getId();//发件人id
            $param['where_is_package'] = 1;//是否是资产包/1是资产包/2是项目
            $param['where_package_project_id'] = $package_id;//资产包id
            $param['where_message_group'] = \Yii::$app->params['GUANZHU_UP'];//资产包id 消息分类 1待审批提醒 2审批反馈 3关注更新
            $param['is_guanzhu'] = 1; //如果是关注，则先删除message_user_group表的信息在添加
            $savePackageMessage = \common\models\InstationMessage::saveMessage($param, $data);
        } else {
            $savePackageMessage['code'] = 200;
            $savePackageMessage['message'] = '编辑成功,无关注用户,没发送消息';
        }
        return $savePackageMessage;
    }
}
